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 :)
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.
JPA implementations deal with persisting instances of your entities classes. that's why the class, methods and variables cannot be final.
@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.
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 ...
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With