Popular via constructor with hibernate

6

I was reading this article link and talks about using builders for popular the objects and set aside some setters. How can I use constructors to populate an object with hibernate? At the time of picking up the form data and saving for example. Is it possible?

    
asked by anonymous 09.01.2016 / 00:15

1 answer

5

The article quoted 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 changeable and expose all their attributes via getters and setters by definition, in addition to having an empty constructor, otherwise you will get an error.

Of course you can have builders or even builders to make it easier to create objects, but this does not remove the general requirements of JPA entities.

A JPA object must be changeable because it is not a simple object, but is managed by the 'EntityManager', so if you want to change some value of an existing entity you should be able to retrieve 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, / em> and with constructors that force the developer to enter all values.

Note that using 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 would maintain these classes, for example to add a new field, I spent several minutes trying to decipher which parameter would stop in which attribute, because the only way to know for sure is to count one by one.

Consider using the builder pattern for classes with multiple attributes. See examples of how this can be done here and #

In short: avoid unnecessary getters and setters, prefer immutable objects, use builders and builders , but unfortunately this will not work with JPA / Hibernate because the context is different.

    
09.01.2016 / 02:57