java – 在CriteriaQuery期间初始化JPA实体的瞬态属性

我想知道在条件查询期间是否可以初始化实体的瞬态属性.

@Entity
public SampleEntity{

  @Id
  private long id;

  [more attributes]

  @Transient
  private String someTransientString;

  [getters and setters]
}

现在我想编写一个CriteriaQuery来加载所有SampleEntity并自动将someTransientString设置为imamightlyf​​inestring.我有类似以下SQL的内容:

SELECT ID AS ID, [..], 'imamightilyfinestring' AS SOME_TRANSIENT_STRING FROM SAMPLE_ENTITY 

我当然知道我可以简单地迭代生成的集合并手动设置属性,但我想知道是否有办法在JPA2中完成它.

谢谢 :)

最佳答案
不,你不能在查询中这样做.

如果你可以在查询之外找出someTransientString的值,你可以使用PostLoad回调(摘自JPA 2.0规范):

The PostLoad method for an entity is invoked after the entity has been
loaded into the current persistence context from the database or after
the refresh operation has been applied to it. The PostLoad method is
invoked before a query result is returned or accessed or before an
association is traversed.

只需向您的实体添加以下内容:

@PostLoad
protected void initSomeTransientString() {
    //Likely some more complex logic to figure out value,
    //if it is this simple, just set it directly in field declaration.
    someTransientString = "imamightilyfinestring";
}

转载注明原文:java – 在CriteriaQuery期间初始化JPA实体的瞬态属性 - 代码日志