Initializing a transient attribute of a JPA entity during CriteriaQuery

后端 未结 2 465
不思量自难忘°
不思量自难忘° 2021-01-04 11:36

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

Example

@Entity
public SampleEntity{

  @         


        
2条回答
  •  囚心锁ツ
    2021-01-04 12:09

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

提交回复
热议问题