Do you write Hibernate code inside POJOs? - java

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

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

Related

Correct way of using CRUD in JSF

I need advice on a few design principles regarding CRUD operations in my JSF project.
A very simple example:
I have a basic screen with a form that get submitted. In my bean I declare a database connection in my method and a string object which I populate with my script. I modify the string to get the data that have been submitted in the form. This is the way I was taught do it, but I'm suspecting it's not based on solid principles.
So I decided to start using prepared statements. Seems a bit better, but still not perfect in my mind.
My question is: instead of writing a new script for each CRUD method, is it better to perhaps create stored procedures instead, in my mind it looks like much neater code and perhaps has better readability.
Or is there an entirely different way of doing things? The only concerns I have is a very fragile OLTP database.
Your JSF,s should always redirect to a servlet which calls a service method, where you write all your business logic and call your Data Access Object to execute required sql query. U should never use your bean for database connection... You should use DataSource for your data base Connection. And yes a simple preparedStatement is enough to do. You should convert all your strings in your servlet only and then pass it to the next layer with the help of your bean which has your setters and getters for all your form fields.. And your DAo contains all the CRUD operations.
I don't like the idea of using stored procedures because they're hard to port and usually also hard to debug.
I've been working for years with something like this
JSF -> xhtml + #ViewScoped managed bean to accomodate the values
Stateless EJB for transactional methods called from managed beans
Entity DAOs, called from EJBs, reusing basic CRUD methods with generics. I think JPA here is great, specially when they use metamodel type-safe criteria (http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html)
Nowadays, it´s been easier to work with lightweight JavaEE stacks such as apache TomEE than using prepared statements.

POJO or DTO approach

I am developing a new web application with Struts2, Spring and Hibernate as its core building blocks.
We have created POJO classes with respect to hibernate mapping files.There will be some inputs from users which needs to be updated in to the underlying database
e.g registration or updation.
We have few option like creating new POJO/DTO for action classes which will be filled by the Struts2 and than we can transfer them to the service layer where we can convert those DTO to the respected hibernate POJO else we can expose same POJO to struts2 so that the framework can fill them with the user input and we need not to do the work for conversion and creating extra set of classes.
Application will be not big in size and will have a medium size application tag.
My question is what is the best way to transfer this user input to underlying hibernate layer to perform data base specific work.
Thanks in advance
I'd prefer the "DTO" approach in this case since you then can validate the input first and trigger updates only when wanted.
However, you could use detached entities as DTOs and reattach them when you want to create or update them. If you don't want the web part of your application to depend on Hibernate and/or JPA you might need to create another set of classes (unless you don't use a single annotation).
You'll get both answers on this.
With Struts 2 I tend to use normal S2 action properties to gather form values/etc. and use BeanUtils to copy them to the Hibernate objects. The problem with exposing the Hibernate objects to the form, like with ModelDriven etc. is that you need to define whitelists/blacklists if you have columns that should not be set directly by the user. (Or handle the problem in a different way.)
That said, I'm not fundamentally opposed to the idea like a lot of people are, and they're arguably correct.

Using POJO as Model in JSF and JPA project, is that right?

i'm developing a project using JSF 2 and JPA 2 (EclipseLink 2.3).
In JSF 2 I learned that we must separate the Model from Controller and the same thing to the View (thanks BalusC).
But now with the POJO's generated from JPA, I wonder if the bean, the model, it should be the pojos now.
My view is gonna be my .xhtml pages, developed in JSF 2.0, that will interact with my controllers then in controllers call the DAO's classes and then operate in my database.
Is this right ? I mean in the concept of MVC ?
I want to do everything right, any tip ?
Thanks in advance.
"MVC" has in JSF multiple points of view. From the high level view, the Model is represented by EJB/JPA and eventually DAO/DTO (if any). The View is represented by your own JSF code (which consits of managed beans and Facelets templates). The Controller is represented by the FacesServlet.
From low level view (a further subdivision of the high level View), the Model is represented by entities or DTOs. The View is represented by your Facelets templates. The Controller is represented by your managed bean. It's basically a M(MVC)C.
Note that "POJO" is a rather legacy term from the old J2EE/Hibernate times. Nowadays, with Java EE/JPA, they're called "Entities". Yes, it are those #Entity Javabeans. Als note that some may opt to use plain vanilla DTOs instead of entities which should decouple your JSF code from the service layer. JSF should then use those DTOs as model and the service layer should in turn map between those DTOs and the real entities. This is in my opinion not necessary. EJB3/JPA2 is a pretty slick API which already minimizes a lot of boilerplate code for which you would have used DAOs/DTOs like as in old J2EE ages. With Java EE 6 and higher, there's not really a need to be able to switch of service layer to for example Spring. Everything is already well thought out and standardized.
See also:
What components are MVC in JSF MVC framework?
Difference between DTO, VO, POJO, JavaBeans?
I found JPA, or alike, don't encourage DAO pattern
Not completely right. It's usally better to avoid referencing model objects directly in the view; you can substitute them with DTO(data transfer object) that just serve the purpose of containing the data to be displayed
Well, in my opinion, this is not correct.
The XHTML pages is the view, but the controller is the JSF servlet (already provided by the framework) and what you call "controller" is actually the model (the business logic). The JPA POJOS are part of the model (the data model).
From the View you should invoke the business logic to obtain the result (as JPA Pojos) and use directly them (no transformation to DTO needed in your architecture) in the view.
Inside your model, you can organice the business logic as you whish (if you think that you need a DAO layer, very common in the industry, you can just put it).

Simple but good pattern for EJB

What would you suggest as a good and practical but simple pattern for a solution with:
HTML + JSP (as a view/presentation)
Servlets (controller, request, session-handling)
EJB (persistence, businesslogic)
MySQL DB
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Should I withdraw business logic from my EJB? All online sources tell me different things and confuses me...
I would definitely put the business logic in Stateless Session Beans. Stateless session beans are nice as they nicely capture the transaction boundaries. And it decouples the View layer from the persistence layer.
Take care that the methods of the SSB correspond to small business goals the user wants to achieve.
Another point is that you must be sure that the data you return has all data in the object tree and that you do not rely on lazy loading to get the rest, because this causes all kind of problems.
Stay as far away as possible from Stateful Session Beans : they are bad news and are a broken concept in the context of a web application.
For long running things, consider using Message Driven Beans which you trigger by sending a JMS message. These are a nice way to do background processing which frees the business logic faster, keeps transactions shorter and returns control to the end user faster.
What would you suggest as a good and practical but simple pattern for a solution with JSP/Servlets + EJB + MySQL
Use the MVC framework of your choice, Stateless Session Beans for the business logic and transaction management (prefer local interfaces if you don't need remoting), Entities for persistence.
Inject your EJBs wherever possible (if you are using Java EE 6, this means anywhere and you can also skip the interface).
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Some might say yes, I say no in most cases. The EntityManager already implements the Domain Store pattern, there is no need to shield it behind a DAO for simple needs.
You might want to read the following resources for more opinions on this:
Has JPA Killed the DAO?,
JPA/EJB3 killed the DAO,
and the more recent DAOs Aren't Dead - But They Either Collapsed Or Disappeared
Should I withdraw business logic from my EJB?
I wouldn't. Put your business logic in your (Stateless) Session Beans. EJB3 are POJOs, they are easily testable, there is no need to delegate the business logic to another layer.
Anno 2012 I would not recommend going for Servlets and JSP as the presentation layer. This was all the rage in 2002, but that's a decade ago.
Today Java EE has an excellent MVC framework build in called JSF. You are much better off using this instead. You most likely want to fetch some Widgets from the component library PrimeFaces, as all the standard ones are a bit basic. A utility library like OmniFaces is a great addition as well.
Regarding the DAOs; don't go as far as directly using the entity manager in (JSF) backing beans, but if you are already using Service classes (transactional boundaries) for your business logic , using a DAO as well might be overkill.
There are still some small advantages of a DAO, like a dao.findByName(...) looks a little clearer than loading a named query, setting a parameter, and getting a (single) result, but the cost is that you have to maintain a seperate DAO for each Entity, probably in addition to some Service.

About Data Objects and DAO Design when using Hibernate

I'm hesitating between two designs of a database project using Hibernate.
Design #1.
(1) Create a general data provider interface, including a set of DAO interfaces and general data container classes. It hides the underneath implementation. A data provider implementation could access data in database, or an XML file, or a service, or something else. The user of a data provider does not to know about it.
(2) Create a database library with Hibernate. This library implements the data provider interface in (1).
The bad thing about Design #1 is that in order to hide the implementation details, I need to create two sets of data container classes. One in the general data provider interface - let's call them DPI-Objects, the other set is used in the database library, exclusively for entity/attribute mapping in Hibernate - let's call them H-Objects. In the DAO implementation, I need to read data from database to create H-Objects (via Hibernate) and then convert H-Objects into DPI-Objects.
Design #2.
Do not create a general data provider interface. Expose H-Objects directly to components that use the database lib. So the user of the database library needs to be aware of Hibernate.
I like design #1 more, but I don't want to create two sets of data container classes. Is that the right way to hide H-Objects and other Hibernate implementation details from the user who uses the database-based data provider?
Are there any drawbacks of Design #2? I will not implement other data provider in the new future, so should I just forget about the data provider interface and use Design #2?
What do you think about this? Thanks for your time!
Hibernate Domain objects are simple POJO so you won't have to create separate DPI-objects, H-Object themselves can be used directly. In DAO you can control whether they come from hibernate or anything else.
I highly recommend reading Chapter 4 "Hitting the database" of Spring in Action, 3rd edition, even if you aren't using Spring in your application. Although my second recommendation would be to use Spring :-)
The DAO pattern is a great way to keep database and ORM logic isolated in the DAO implementation, and you only need one set of entity objects. You can make that happen without Spring, it just takes more work managing your sessions and transactions.
If I understand your post, this is sort of a middle-ground between Design 1 and Design 2. The H-Objects (the entities that Hibernates loads and persists) don't need any Hibernate specific code in them at all. That makes them perfectly acceptable to be used as your DPI-Objects.
I've had arguments with folks in the past who complain that the use of JPA or Hibernate Annotations exposes Hibernate specifics through the DAO interface. I personally take a more pragmatic view, since annotations are just metadata, and don't directly affect the operation of your entity classes.
If you do feel that the annotations expose too much, then you can go old school and use Hibernate Mappings instead. Then your H-Objects are 100% Hibernate free :-)
I recommend design #2. Simply construct domain objects, and let hibernate look after them. Don't write separate classes that are persisted.
Hibernate tries to hide most of the persistence business from you. You may need to add a few small annotations to your entities to help it along. But certainly don't make separate classes.
You may need some very small DAO classes. For example, if you have a Person entity, it would be fairly common practice to have a PersonDAO object that saves a person. Having said that, the code inside the DAO will be very simple, so for a really small project, it may not be worth it. For a large project, it's probably worth keeping your persistence code separate from your business logic, in case you want to use a different persistence technology later.

Categories