Lombok @Builder and JPA Default constructor

前端 未结 8 1884
遇见更好的自我
遇见更好的自我 2020-12-04 11:03

I\'m using project Lombok together with Spring Data JPA. Is there any way to connect Lombok @Builder with JPA default constructor?

Code:



        
8条回答
  •  时光取名叫无心
    2020-12-04 11:17

    To use the following combination

    • lombok
    • JPA
      • CRUD
      • proper @EqualsAndHashCode
    • immutability - public final fields
    • no getters
    • no setters
    • changes via @Builder and @With

    I used:

    //Lombok & JPA
    //https://stackoverflow.com/questions/34241718/lombok-builder-and-jpa-default-constructor
    
    //Mandatory in conjunction with JPA: an equal based on fields is not desired
    @lombok.EqualsAndHashCode(onlyExplicitlyIncluded = true)
    //Mandatory in conjunction with JPA: force is needed to generate default values for final fields, that will be overriden by JPA
    @lombok.NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
    //Hides the constructor to force usage of the Builder.
    @lombok.AllArgsConstructor(access = AccessLevel.PRIVATE)
    @lombok.ToString
    //Good to just modify some values
    @lombok.With
    //Mandatory in conjunction with JPA: Some suggest that the Builder should be above Entity - https://stackoverflow.com/a/52048267/99248
    //Good to be used to modify all values
    @lombok.Builder(toBuilder = true)
    //final fields needed for imutability, the default access to public - since are final is safe 
    @lombok.experimental.FieldDefaults(makeFinal = true, level = AccessLevel.PUBLIC)
    //no getters and setters
    @lombok.Getter(value = AccessLevel.NONE)
    @lombok.Setter(value = AccessLevel.NONE)
    
    //JPA
    @javax.persistence.Entity
    @javax.persistence.Table(name = "PERSON_WITH_MOTTO")
    //jpa should use field access 
    @javax.persistence.Access(AccessType.FIELD)
    public class Person {
      @javax.persistence.Id
      @javax.persistence.GeneratedValue
      //Used also automatically as JPA
      @lombok.EqualsAndHashCode.Include
      Long id;
      String name;
      String motto;
    }
    

提交回复
热议问题