Can I use the builder design pattern together with hibernate?
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 hibernate annotations开发者_Go百科 to map it to a table?
Yes and no. You can use it if you also provide setters.
Hibernate uses Java Beans to access the properties, so it relies on getXXX()
and setXXX()
methods being present. The whole point of the builder pattern (at least according to Joshua Bloch) is to create immutable objects without setters. This won't work with Hibernate (or any ORM), as they use the setters to inject the values.
But if you just want to use your builder API as a fluent interface to generate the objects while leaving their getters and setters intact, then there's of course no harm in that (other than that it's a duplication of code).
BTW: Fluent setters are not valid Java Beans setters. The Introspector
mechanism does not understand them. Setters must have a void return type.
The builder is an external mechanism for creating objects. It is sufficient that you provide a default constructor to your entity, and hibernate would not care how you obtained it. So yes - it is possible, just like a normal entity.
精彩评论