简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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