实体继承与@Builder注解共存

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

下面做一个Jpa实体的例子

一个基类

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

注意:父类中的属性需要子数去访问,所以需要被声明为protected,如果是private,那在赋值时将是不被允许的。

/**
* @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();
}
}

一个实现类

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

@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());
}
上一篇:用FSM写Case,玩过没?


下一篇:小程序ios开发注意点