内容简介:在面向对象的设计里,继承是非常必要的,我们会把共有的属性和方法抽象到父类中,由它统一去实现,而在进行lombok时代之后,更多的打法是使用@Builder来进行对象赋值,我们直接在类上加@Builder之后,我们的继承就被无情的屏蔽了,这主要是由于构造方法与父类冲突的问题导致的,事实上,下面做一个Jpa实体的例子它一般有统一的id,createdOn,updatedOn等字段 ,在基类中统一去维护。
在面向对象的设计里,继承是非常必要的,我们会把共有的属性和方法抽象到父类中,由它统一去实现,而在进行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());
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 飞特 3.1,商城与后台起飞,模板与注解共存
- 飞特 3.1,商城与后台起飞,模板与注解共存
- 安全与公平共存的智慧城市
- Centos多版本php共存
- Spring Cloud与Dubbo共存方案总结
- Unity UI 显隐(共存)关系的优化处理方案
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Jakarta Struts Cookbook中文版
斯格科 / 清华大学 / 2007-7 / 56.00元
Jakarta Struts Cookbook(中文版),ISBN:9787302155638,作者:(美)斯格科一起来看看 《Jakarta Struts Cookbook中文版》 这本书的介绍吧!