简体   繁体   English

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

[英]Initializing a transient attribute of a JPA entity during CriteriaQuery

I'm wondering if it is possible to initialize a transient attribute of an entity during a criteria query. 我想知道在条件查询期间是否可以初始化实体的瞬态属性。

Example

@Entity
public SampleEntity{

  @Id
  private long id;

  [more attributes]

  @Transient
  private String someTransientString;

  [getters and setters]
}

Now I want to compose a CriteriaQuery that loads all SampleEntity s and automatically sets someTransientString to imamightlyfinestring . 现在我想SampleEntity一个CriteriaQuery来加载所有SampleEntity并自动将someTransientString设置为imamightlyfinestring I have something like the following SQL in mind: 我有类似以下SQL的内容:

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

I of course know that I can simply iterate the resulting collection and manually set the attribute, but I'm wondering if there is a way to do it within JPA2. 我当然知道我可以简单地迭代生成的集合并手动设置属性,但我想知道是否有办法在JPA2中完成它。

Thanks :) 谢谢 :)

No, you cannot do it in query. 不,你不能在查询中这样做。

If you can figure out value for someTransientString outside of query, you can use PostLoad callback (excerpt from JPA 2.0 specification): 如果你可以在查询之外找出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. 在将实体从数据库加载到当前持久性上下文之后或者在对其应用刷新操作之后,调用实体的PostLoad方法。 The PostLoad method is invoked before a query result is returned or accessed or before an association is traversed. 在返回或访问查询结果之前或遍历关联之前调用PostLoad方法。

Just add following to your entity: 只需向您的实体添加以下内容:

@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";
}

You can also initialize your transients in the default (ie, no argument) constructor. 您还可以在默认(即无参数)构造函数中初始化瞬变。

You can see that this is the strategy used, for example, in EclipseLink (read last comment in the following link): 您可以看到这是使用的策略,例如,在EclipseLink中(阅读以下链接中的最后一条评论):

https://bugs.eclipse.org/bugs/show_bug.cgi?id=292385 https://bugs.eclipse.org/bugs/show_bug.cgi?id=292385

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM