在CriteriaQuery期间初始化JPA实体的瞬态属性 [英] Initializing a transient attribute of a JPA entity during CriteriaQuery

查看:408
本文介绍了在CriteriaQuery期间初始化JPA实体的瞬态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if it is possible to initialize a transient attribute of an entity during a criteria query.

示例

@Entity
public SampleEntity{

  @Id
  private long id;

  [more attributes]

  @Transient
  private String someTransientString;

  [getters and setters]
}

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

Now I want to compose a CriteriaQuery that loads all SampleEntitys and automatically sets someTransientString to imamightlyfinestring. I have something like the following SQL in mind:

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

我当然知道我可以简单地迭代生成的集合并手动设置属性,但是我我想知道在JPA2中是否有办法做到这一点。

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.

谢谢:)

推荐答案

不,你不能在查询中这样做。

No, you cannot do it in query.

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

If you can figure out value for someTransientString outside of query, you can use PostLoad callback (excerpt from JPA 2.0 specification):


实体的PostLoad方法是在
从数据库加载到当前持久化上下文之后或在
之后应用刷新操作之后调用的。在返回或访问查询结果之前或遍历
关联之前,PostLoad方法是

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.

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

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

这篇关于在CriteriaQuery期间初始化JPA实体的瞬态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆