Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the builder design pattern together with hibernate?

Tags:

java

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 to map it to a table?

like image 640
Yossi Avatar asked Jan 17 '11 13:01

Yossi


2 Answers

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.

like image 154
Sean Patrick Floyd Avatar answered Oct 16 '22 12:10

Sean Patrick Floyd


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.

like image 39
Bozho Avatar answered Oct 16 '22 14:10

Bozho