Can I use the builder design pattern with sleep mode?

Assuming I have this class:

public class MyEntity { private int id; private String name; private MyEntity(int id, String name) {this.id= id; this.name = name;} public static class MyEntityBuilder { private int id; private String name; private MyEntityBuilder setId(int id) {this.id = id;} private MyEntityBuilder setName(String name) {this.name = name;} private MyEntity build() {return new MyEntity(id,name);} } private int getId() {return id;} private String getName() {return name;} } 

Can I use sleep mode annotations to map it to a table?

+8
java hibernate
source share
2 answers

Yes and no. You can use it if you also provide setters.

Hibernate uses Java Beans to access properties, so it relies on the getXXX() and setXXX() methods. The whole purpose of the builder pattern (at least according to Joshua Bloch) is to create immutable objects without setters. This will not work with Hibernate (or any ORM), as they use installers to enter values.

But if you just want to use your builder API as a free interface for creating objects, leaving their getters and setters intact, then of course there is no harm (except that this is code duplication).

BTW: Free Setters are not valid Java Beans Setters. The Introspector mechanism does not understand them. Setters must have a void return type.

+5
source share

A constructor is an external mechanism for creating objects. It is enough that you provide a default constructor for your object, and hibernation would not care about how you got it. So yes - it is possible, as an ordinary object.

+4
source share

Source: https://habr.com/ru/post/651166/


All Articles