Reputation: 39
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?
Upvotes: 0
Views: 2799
Reputation: 1717
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.
Upvotes: 6
Reputation: 18410
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);
Upvotes: 2