Search code examples
javahibernatejspservletspojo

Do you write Hibernate code inside POJOs?


We have a web application which uses JSP, Servlet and Hibernate. The design pattern we got is MVC like, which means,

JSP -> Servlet -> Beans (POJO)

Now the question. Once of out developers has inserted the hibernate queries, hibernate session creation etc inside POJOs. Now inside these POJOs, there are methods like getAllEmployees(), getAllAgents() etc. This made it extremely hard for us to change the database tables (we handle database manually, using MySQL Workbench) and use automatic tools to re-generate the POJOs because these methods will be lost.

Now there are 2 arguments. One is that this maintaining hibernate queries, sessions inside POJOs is a good work, because it seems like pure MVC. The other argument is move the hibernatre code to Servlets and call the POJOs just like beans, only to set and get values.

We have not worked in Hibernate before. From above 2, what is the preferred place to write hibermnate code when it comes to hibernate?

Finally, please note we are not interested in Spring or other frameworks, we use pure JSP and Servlet with Hibernate


Solution

  • Probably, what you need is another layer of abstraction. Since your pojos are recreated after new migrations, you shouldn't insert code in it (I don't agree with that aproach, but that's just my opinion :-) )

    JSP -> Servlet -> NewLayer -> POJO

    I don't know where you put your business rules, but in this scenario it will be in the "NewLayer" wich would consist of a "hibrid" layer of service and dao.

    I would recommend these readings to rethink your actual architecture:

    https://softwareengineering.stackexchange.com/questions/220909/service-layer-vs-dao-why-both

    Responsibilities and use of Service and DAO Layers