Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can hibernate business objects be used as entities in a clean architecture?

In our project we use classes generated by eclipse hibernate plugin for persistence. The generated classes have following structure.

MyClass extends BaseMyClass //POJO's, that are refenced in the hbm
files

MyClassDAO extends BaseMyClassDAO //DAO objects that use hibernate
session objects to provide CRUD API's for working with DB

My question is, would it violate Uncle Bobs clean architecture if we use the POJO classes used in the mapping files as the Entities in the innermost layer.

The hibernate specific DAO classes would belong in this case to the outermost layer and UseCases layer would communicate with this layer via providing an interface to be implemented.

like image 259
Aleksandr Burnazyan Avatar asked Nov 20 '22 04:11

Aleksandr Burnazyan


1 Answers

Uncle Bob comments on this during a lecture in Norway while presenting this slide:

Entity Gateway

Uncle Bob says:

There is no Hibernate above the line. If you are using Hibernate it goes below the line. The application does not know that you are using that framework. It goes below the line. And Hibernate is a lovely tool. It's very good for gathering data out of the database and turning it into data structures. Very nice! But you don't want your application to know that you are using it. You put all that stuff below the line.

Robert C Martin - Clean Architecture, NDC 2012 (53:53 - 54:18)

Thus if you are using Hibernate annotations on the entities, you mix your domain objects with details of the database layer.

Some developers argue that annotations are not so strong dependencies, because if they are not available at runtime they just do not exist. That's true, but you also have to consider other principles.

If you put Hibernate annotations on your entities, the entity classes now have two different reasons to change: the domain logic and the database mapping. This is a violation of the single responsibility principle. Therefore database mappings will affect your domain objects.

I guess there is a lot of confusion, because of the overloaded term entity. When Uncle Bob talks about entities he means domain. In Hibernate entity means database record.

That's why I usually distinguish them by using the term "domain entity" or "database entity".

like image 103
René Link Avatar answered Dec 21 '22 23:12

René Link