Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 482
ftr Avatar asked Apr 25 '12 10:04

ftr


People also ask

What does transient mean in JPA?

Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's @Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different.

What in JPA Cannot contain final fields or methods while mapping?

JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.

Which annotation in JPA specifies whether the entity field can be null or not?

@Basic annotation's optional attribute defines whether the entity field can be null or not; on the other hand, @Column annotation's nullable attribute specifies whether the corresponding database column can be null.

Which are JPA entity fields?

Using JPA, you can designate any POJO class as a JPA entity–a Java object whose nontransient fields should be persisted to a relational database using the services of an entity manager obtained from a JPA persistence provider (either within a Java EE EJB container or outside of an EJB container in a Java SE application ...


1 Answers

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";
}
like image 193
Mikko Maunu Avatar answered Oct 15 '22 15:10

Mikko Maunu