Fluent API entity building with JPA and Hibernate

Introduction

The JHipster development team wants to expose Fluent Interface entity building methods for their JPA entities, so they asked me if this is going to work with JPA and Hibernate. While JPA is rather strict about entity getters and setter, Hibernate is more lenient in this regard.

JPA specification

It is required that the entity class follow the method signature conventions for JavaBeans read/write
properties (as defined by the JavaBeans Introspector class) for persistent properties when property
access is used.

In this case, for every persistent property property of type T of the entity, there is a getter method, getProperty, and setter method setProperty. For boolean properties, isProperty may be used as an alternative
name for the getter method.[2]

For single-valued persistent properties, these method signatures are:

• T getProperty()
• void setProperty(T t)

The reason why we get such a requirement is because the JPA specification makes no assumption regarding how entities are going to be used. By adhering to the Java Bean specifications, entities can be introspected using Java Reflection by IDE tools or other frameworks that might expect this standard getter and setter signature.

Although this generic alternative is better from a portability perspective, if your enterprise application does not rely on Java Bean compliant setters, you are better off changing the setter signature according to the Fluent Interface pattern requirements.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

The Fluent Interface pattern works just fine with Hibernate, so one more reason to consider it the JPA provider of choice.