Spring Data JPA - how to set transient fields afte

2019-02-28 15:00发布

After an entity is fetched using the JpaRepository methods of Spring Data JPA, e.g. findOne, findBy..., etc., I was wondering what would be the best way to automatically execute some custom code, say to initialize some transient fields.

In other words, suppose I have a User entity with a fullName transient field, which should be set as a concatenation of firstName and lastName after fetching from the database, what should I do?

3条回答
劫难
2楼-- · 2019-02-28 15:11

Firstly, if all you want if full name just write a method that concatenates forename/surname on the fly. It doesn't have to be a field.

If you really need to do some processing on Entity load then register a @PostLoad entity lifecycle callback:

public class MyEntity{

     @PostLoad
     //invoked by framework on entity load.
     public void doStuff(){
         fullName =  forename + " " + surname;   
     }

     //alternative
     public String getFullName(){
         return forename + " " + surname;
     }

https://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Example_of_Entity_event_annotations

查看更多
▲ chillily
3楼-- · 2019-02-28 15:29

Have not tried myself but it seems that the @PostLoad annotation may help you to execute code to change the state of a business object after retrieving it from the database.

But in your concrete case I would simply create a method getFullName that concatenates firstName and secondName without storing the value in the bean.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-28 15:30

You can use @Access(AccessType.Property) for setting transient fields ideally.

You have to mention @Access(AccessType.Property) on the setter method normally and then you can set value of that transient field in that setter method.

Alternatively in case of repositories , you can very well write a JPQL something like this.

@Query("SELECT new Hello(a.x*a.y,a.x,a.y)FROM Hello a WHERE t.value = :value")

and then in the constructor set the value of this transient variable with a.x*a.y

查看更多
登录 后发表回答