实体继承与@Builder注解共存

在面向对象的设计里,继承是很是必要的,咱们会把共有的属性和方法抽象到父类中,由它统一去实现,而在进行lombok时代以后,更多的打法是使用@Builder来进行对象赋值,咱们直接在类上加@Builder以后,咱们的继承就被无情的屏蔽了,这主要是因为构造方法与父类冲突的问题致使的,事实上,咱们能够把@Builder注解加到子类的全参构造方法上就能够了!app

下面作一个Jpa实体的例子单元测试

一个基类

它通常有统一的id,createdOn,updatedOn等字段 ,在基类中统一去维护。测试

注意:父类中的属性须要子数去访问,因此须要被声明为protected,若是是private,那在赋值时将是不被容许的。ui

/**
 * @MappedSuperclass是一个标识,不会生成这张数据表,子类的@Builder注解须要加在重写的构造方法上.
 */
@Getter
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@MappedSuperclass
public abstract class EntityBase {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  protected Long id;


  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @Column(name = "created_on")
  protected LocalDateTime createdOn;

  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  @Column(name = "updated_on")
  protected LocalDateTime updatedOn;

  /**
   * Sets createdAt before insert
   */
  @PrePersist
  public void setCreationDate() {
    this.createdOn = LocalDateTime.now();
    this.updatedOn = LocalDateTime.now();
  }

  /**
   * Sets updatedAt before update
   */
  @PreUpdate
  public void setChangeDate() {
    this.updatedOn = LocalDateTime.now();
  }
}

一个实现类

注意,须要重写全参数的构造方法,不然父数中的属性不能被赋值。this

@Entity
@Getter
@NoArgsConstructor
@ToString(callSuper = true)
public class TestEntityBuilder extends EntityBase {
  private String title;
  private String description;

  @Builder(toBuilder = true)
  public TestEntityBuilder(Long id, LocalDateTime createdOn, LocalDateTime updatedOn,
                           String title, String description) {
    super(id, createdOn, updatedOn);
    this.title = title;
    this.description = description;
  }
}

单元测试

/**
   * 测试:在实体使用继承时,如何使用@Builder注解.
   */
  @Test
  public void insertBuilderAndInherit() {
    TestEntityBuilder testEntityBuilder = TestEntityBuilder.builder()
        .title("lind")
        .description("lind is @builder and inherit")
        .build();
    testBuilderEntityRepository.save(testEntityBuilder);
    TestEntityBuilder entity = testBuilderEntityRepository.findById(
        testEntityBuilder.getId()).orElse(null);
    System.out.println("userinfo:" + entity.toString());

    entity = entity.toBuilder().description("修改了").build();
    testBuilderEntityRepository.save(entity);
    System.out.println("userinfo:" + entity.toString());
  }
相关文章
相关标签/搜索