简体   繁体   中英

Lombok @Data and @Builder combination

Hi I have a question about @Data and @Builder combination. Let's imagine the situation: I have Entity which has to be created and modified. Firstly I create it:

Entity entity = Pojo.builder()
.a("1")
.b("2")
.build();

After some operations, I have to add c field and modify a . How I have to do that? Is this normal to do:

entity.setA("01");
entity.setC("3");
repo.save(entity);

Is there any better variants?

That's fine. Buider -> object creation, Set -> object setting after creation.

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

You can use setter always using @Accessors(chain = true) on entity to create object and to set field. The chain option gives us setters that return this.

Entity entity= new Entity().setName("Name").setBalance(10);
entity.setName("newName");

Note that chain defaults to true, but I set it explicitly for clarity.

And for accessors without get or set prefix use @Accessors(fluent = true)

Entity entity= new Entity().name("Name").balance(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM