Initializing a transient attribute of a JPA entity during CriteriaQuery

老子叫甜甜 提交于 2019-11-30 02:36:43

问题


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 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 

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.

Thanks :)


回答1:


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):

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



回答2:


You can also initialize your transients in the default (i.e., no argument) constructor.

You can see that this is the strategy used, for example, in EclipseLink (read last comment in the following link):

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



来源:https://stackoverflow.com/questions/10313535/initializing-a-transient-attribute-of-a-jpa-entity-during-criteriaquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!