当前位置: 移动技术网 > IT编程>开发语言>Java > 实体继承与@Builder注解共存

实体继承与@Builder注解共存

2019年01月15日  | 移动技术网IT编程  | 我要评论

在面向对象的设计里,继承是非常必要的,我们会把共有的属性和方法抽象到父类中,由它统一去实现,而在进行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());
  }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网