Spring Data JPA - how to set transient fields after retrieval

前端 未结 3 900
遇见更好的自我
遇见更好的自我 2021-01-22 16:41

After an entity is fetched using the JpaRepository methods of Spring Data JPA, e.g. findOne, findBy..., etc., I was wondering what would b

3条回答
  •  长发绾君心
    2021-01-22 17:21

    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

提交回复
热议问题