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.
Related
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
I currently work on a legacy application.
This application uses spring (3.1.0.RELEASE) and hibernate (3.6.9.Final).
In some DAO, there is a mix of hibernateTemplate and jdbcTemplate.
I think that the developers finally use jdbcTemplate to simplify the select request.
What do you think of that ?
What are the potentials impacts of this type of mixture (cache pb ...)?
Have you ever encountered this kind of code?
There is no problem with mixing jdbcTemplate (native sql) with hibernateTemplate (hql) in same transaction. Our team use that pattern in same (rare) situations. But it is important to have single method in single convention.
For example in one method you fetches set of IDs that satisfy some business logic (and this is easier of efficient to write this in SQL) and then you pass those IDs to other method that run some HQL using these IDs because it is more convenient there.
But for maintanance reasons it is good to have different conventions isolated in different methods. Of course this may be wrapped in on TX call.
Final note: when I decide to write project with hibernate I mean that hibernate is dominant technology and when some data can be fetched easier or significantly faster in other technology I will use other technology to do that.
Anyway you have to know all issues with hibernate caching and postponed flush and so on.
If you want your project to be successful create code conventions and rules that all developers will follow.
Code should look like it was written by one person.
Note: so do not mix HibernateTemplate and JdbcTemplate.
I am developing web application with Java EE 6. In order to minimize calls to database will it be a good idea to have classes:
Data access class (DAO) will call only basic methods getAllClients, getAllProducts, getAllOrders, delete, update methods - CRUD methods.
Service class which will call CRUD methods but in addition filter methods e.g. findClientByName, findProuctByType, findProductByYear, findOrderFullyPaid/NotPaid etc... which will be based on basic DAO methods.
Thank you
In my experience (albeit, limited) DAO classes tend to have all the possible database operations which the application is allowed to perform. So in your case, it will have methods such as getAllClients() and getClientByName(String name), etc.
Getting all the users in your DAO and iterating all over them until you find the one you need will result in unneeded waste of computational time and memory consumption.
If you want to reduce the amount of times that your database is hit you could, maybe, implement some caching mechanism. An ORM framework such as Hibernate should be able to provide what you need as shown here.
EDIT:
As per your comment question, no, your service will not be made redundant. What one does is to usually use a Service layer to expose the DAO functionalities. This will, basically, not make the DAO visible from the from front end of your application. It usually also allows for extra methods, such as, for instance, public String getUserFormatted(String userName). This will make use of the getUserByName function offered by the DAO but provide some extra functionality.
The Service layer will also make itself useful should there be a change in specification and you now also need a web service to interface with your application. Having a service layer in between will allow the web service to query the DAO through the Service layer.
So basically, the DAO layer will still worry about the database stuff (CRUD Operations) while the service will adapt the data returned by the DAO without exposing the DAO.
It's hard to say without more information, but I think it's probably a good idea to leverage your database more than with just CRUD operations. Databases are good at searching, provided you configure them correctly, so IMHO it's a good idea to let your database handle the searching in your find methods for you. This means that your find methods would probably go in your DAOs...
It's good to think about/be aware of the implications of DB access on performance, but don't go overboard. Also, your approach implies that since your services are going to be doing the filtering, you are going to load a large amount of DB data into your application, which is a bad idea. The bottom line is you should use your RDBMS as it is intended to be used, and worry about performance due to over-access when you can show its a problem. I doubt you will run into that scenario.
I would say that you're better off having your DAO be more fine grained than you've specified.
I'd suggest putting findClientByName, findProuctByType, findProductByYear, findOrderFullyPaid/NotPaid on your DAO as well in some way because your database will most likely be better at filtering and sorting data than your in memory code.
Imagine you have 10 years of data and you call findProductsByYear on your service class and it then calls getAllProducts and then throws away 9 years of data in memory. You're far better off getting your database to only return you the year you are interested in.
Yes, this is the right way to do it.
The service will own the transactions. You should write these as POJOs; that way you can expose them as SOAO or REST web services, EJBs, or anything else that you want later on.
I just started a simple Java testproject which manages some entities using Hibernate and provides a REST interface to manipulate these objects and provide some additional business logic. The REST interface is created using RESTEasy and Jetty.
Everything works fine so far, but I have the feeling that I'm actually writing too much boilerplate code. As I don't have much experience in these Java frameworks I'm just wondering if anyone could give me a hint on how to improve the situation.
Creting Hibernate Sessions per Request
Well, as far as I understood I have to create a Hibernate session per request and at the end I have to close it. So currently all of my service methods look like this:
Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
...
...
...
session.close();
Is there any way to remove these two lines in order to somehow do this automatically?
Currently my service is registered as a RestEASY singleton. Will changing to a RESTeasy ressource and creating the session in the constructor solve the problem? I think it will solve the problem of creating the session. But wherer to close it?
In C++ this can easily done be creating a scoped object which closes the session at the end. But in Java?
Whenever such a REST request is made I have to check for a valid session (the user has to login previously). Is a ServletFilter the right way to do this?
General: Are there any other patterns or frameworks I should consider using? I mean I want to keep it as simple as possible and especially as I dont have that much experience I dont want to end up using Spring or whatever heavyweight framework. Seems that I'm used to the simplicity of Python and Django but for this little project I have to use Java.
THanks so far!
Hibernate's current recommended approach for managing Sessions is detailed on this wiki page. In particular, I think you need to read the last paragraph: This is all very difficult, can't this be done easier?
In the end, you do need to tell the persistence layer that "I'm about to do something" (which usually also gets the Session to do it with) and "I'm done doing it". You can do it with annotations, or JTA transactions, but that information still has to be communicated!
Inject SessionFactory to your Data Access Object and use sessionFactory.getCurrentSession() to access Hibernate Session object.
you can make use of any of the Factory classes available to implement this..
Then your code should look like this..
sessionFactory.getCurrentSession().save(newInstance);
You should try writing a Filter that does this. Spring's OpenSessionInViewFilter is a good place to start if you need an example.
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.