Popular via builder with Hibernate

Asked

Viewed 235 times

6

1 answer

5


The cited article talks about the unnecessary use of getters and setters. This concept is correct and the subject has already been discussed here by some people, including me, for example:

However, something that is good practice in general does not necessarily work in all contexts.

JPA or Hibernate entities are an example, because they are not immutable entities, on the contrary, they need and must be mutable and expose all their attributes via getters and setters by definition, besides having an empty constructor, otherwise you will receive an error.

Of course you can have builders or even Builders to facilitate object creation, but this does not remove general JPA entity requirements.

A JPA object needs to be mutable because it is not a simple object but is managed by 'Entitymanager', so if you want to change some value of an existing entity you should be able to recover the JPA instance and change its values.

This also does not mean that you need to use these mutable objects throughout your program. It is quite possible to use JPA entities to interface with the database while exposing this data to other layers of the system using transfer Objects (Tos or Dtos), these immutable, without setters and with constructors that force the developer to report all values.

Note that the use of constructors, while interesting, often becomes confusing with entities that have many attributes. An arbitrary rule says that more than five parameters in a method makes it difficult to use. I have seen Dtos with 30 or 50 parameters in the constructor and, to make matters worse, several constructors. Each time someone was going to maintain these classes, for example to add a new field, they spent several minutes trying to decipher which parameter would stop at which attribute, because the only way to know for sure is to count one by one.

Consider the use of the pattern Builder for classes with multiple attributes. See examples of how this can be done here and here.

In short: avoid getters and setters unnecessary, prefer immutable objects, use constructors and Builders, but unfortunately, it won’t work with JPA/Hibernate because the context is different.

  • Thanks, you’ve made my doubts clear.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.