Hibernate: sessionFactory.openSession() VS sessionFactory.getCurrentSession() - java

I am trying to make a web application in Spring 4(Java Configuration). I am using postgres as database and C3P0 as connection pool.
All my database transactions are happening in postgres stored procedures/ functions. I am using Hibernate #NamedNativeQueries to call the stored procedures.
I have 2 questions:
1. My application will have multiple users logged in at same time. SO should i use sessionFactory.openSession() or sessionFactory.getCurrentSession() for getting hibernate session?
2. shall i use hibernate to call stored procedures or build in support in spring mvc4? i know both ways but i am more comfortable with hibernate as it needs very less efforts compared to spring way but i feel hibernate is making my application slow but not sure.
Please help me in finding answers to these questions.

Answer to the first question :
you should have a session per user connected. For example, if you are in a servlet context, you can have a servlet filter to call sessionFactory.openSession() per servlet thread.
Answer to the second question :
performance and optimisation is not a feeling. If you feel hibernate slow, measure it and try to know why. You have to measure where it slows. You can also try both solutions with a simple example and know where you feel more comfortable.

Related

Hibernate query already fetched entities

Is there a way in hibernate(or ORM in general) to query session managed collections, i.e get entity with max id, without hitting the database.
Right now I do this with Java stream API. It works and it is much faster than a database query. But I find myself doing this a lot in my current project. So I thought hibernate might already have an option to run queries "locally".
It is an desktop application so i am sure the DB won't change outside of this application.
No #lazyCoding, HIBERNATE can't do it. Maybe http://josql.sourceforge.net/manual/introduction.html will help you.

Retrieving objects with associations in Spring JDBC

I am fairly new to using Spring JDBC and I am going to retrieve objects from the database now which have associations to other objects (one-to-many, one-to-one...). I wonder what is the proper way of doing it? I have read this answer Spring Framework JDBC DAO with agrgegation/composition which basically recommends using a ORM framework which I won't cause of performance and I find Spring JDBC quite pleasant to work with.
The original poster of the question showed an example of using one repository/dao method inside another dao/repository class. That would have been my guess of doing it too, but from what I understand you then use two different connections, and it could increase if you have other repositories as well. Is this bad even though using connection pooling provided by Glassfish?
I am not sure if I understand the answer given to the question either, nor if this is the proper way of doing it?
Spring JDBC always used the same connection in the scope of a transaction, so you should not worry about the number of connections, you only need to ensure that the load of the object occurs within a single transaction.
see DataSourceUtils.doGetConnection() if you are interested on how connections are retrieved from data source.

An Interview on Hibernate Integration

I went to an interview into a IT consultancy company last friday.
The Interviewer asked me about my project and what was my participation in it.
Suddenly he threw one question on hibernate. His question was as follows
"If i have an project which has been developed in an MVC architecture using Java EE environment, but using JDBC for Database interaction, how will i integrate Hibernate into it. I don't want to disturb the existing code, all the previous JDBC code should be intact. "
I told him that we an add all the features of hibernate in the existing code, as it only requires Config files, Entities thats it. The old code of JDBC may itself be using Datasourse for getting connection, the same datasourse can be looked up using JNDI to build a session factory in Hibernate, not a big deal.
But the interviewer was not happy with my answer, he needed some more explanation.
I was not able to impress him.
So can you please suggest what should be the probable answer for the above question.
Or at least give me one hint so that i can come to an answer.
I think he wanted answer like the following.
Typical application design requires layers separation. There are the following classic layers: web tier, business logic and DB. There is a thin layer named DAO (Data Access Objects) that is written in java and plays a role of "middleman" between business logic and DB. It sounds that this tier is implemented using plain JDBC.
So, there is not a problem to replace this and only this layer with Hibernate based one.
Now you can add more details about how you are configuring Hibernate and integrate it with the rest of your application.
Not an exact answer and you did not mention which framework your application use but if your application uses Spring framework, this my question and its answer's will be helpful to you but my question is reverse as I wanted to integrate jdbc with hibernate.
I think he was probably looking for you to explain how you might:
put Hibernate wrappers around existing SQL queries, or
create Hibernate bindings for legacy SQL tables, or
integrate Hibernate and classic JDBC using container-level transactions.
(It is clear that he was not asking about how you would replace the old JDBC code with Hibernate code ...)
But of course, you'd really need to ask him what knowledge / experience he was expecting you to demonstrate in answering the question.

Hibernate multiple users, dynamically changing

There are technically two questions here, but are tightly coupled :)
I'm using Hibernate in a new project. It's a POS project.
It uses Oracle database.
We have decided to use Hibernate because the project is large, and because it provides (the most popular) ORM capabilities.
Spring is, for now, out of the question - the reason being: the project is a Swing client-server application, and it adds needless complexity. And, also, Spring is supposed to be very hungry on the hardware resources.
There is a possibility to throw away Hibernate, and to use JDBC. Why? The project requirement is precise database interaction. Meaning, we should have complete control over the connections, sessions and transactions(and, yes, going as low as unoptimized queries).
The first question is - what are your opinions on using the mentioned requrement?
The second question revolves around Hibernate.
We developed a simple Hibernate pilot project.
Another project requirement is - one database user / one connection per user / one session per user / transactions are flexibile(we can end them when we want, as sessions).
Multiple user can log in the application at the same time.
We achived something like that. To be precise, we achived the full described functionality without the multiple users requirement.
Now, looking at the available resources, I came to a conclusion that if we are to have multiple users on the database(on the same schema), we will end up using multiple SessionFactory, implementing a dynamic ConnectionProvider for new user connections. Why?
The users hashed passwords are in the database, so we need to dynamically add a user to the list of current users.
The second question is - can this be done a little easier, it seems weird that Hibernate doesn't support such configurations.
Thank you.
If you're pondering about weather to use Hibernate or JDBC, honestlly go for JDBC. If your domain model is not too complex, you don't really get a lot of advantages from using hibernate. On the other hand using JDBC will greatly improve performance, as you have better control on your queries, and you get A LOT less memory usage from not habing all the Hibernate overhead. Balance this my making an as detailed as possible first scetch of your model. If you're able to schetch it all from the start (no parts that are possible to change wildly in throughout the project), and if said model doesn't look to involved, JDBC will be your friend.
About your users and sessions there, I think you might be mistaking (tho it could just be me), but I don't think you need multiple SessionFactories to have multiple sessions. SessionFactory is a heavy object to initialize, but once you have one you can get multiple hibernate session objects from it which are lightweight.
As a final remark, if you truly stick with an ORM solution (for whatever reason), if possible chose EclipseLink JPA2 implementation. JPA2 has more features over hibernate and the Eclipselink implementation is less buggy then hibernate.
So, as far as Hibernate goes, I still dont know if the only way to dynamicaly change database users(change database connections) was to create multiple session factories, but I presume it is.
We have lowered our requriements, and decided to use Hibernate, use only one user on the database(one connection), one session per user(multiple sessions/multiple "logical" users). We created a couple of Java classes to wrap that functionality. The resources how this can be done can be found here.
Why did we use Hibernate eventually? Using JDBC is more precise, and more flexibile, but the effort to once again map the ResultSet values into objects is, again, the same manual ORM approach.
For example, if I have a GUI that needs to save a Page, first I have to fetch all the Page Articles and then, after I save the Page, update all the Articles FK to that Page. Notice that Im speaking in nouns(objects), and I dont see any other way to wrap the Page/Articles, except using global state. This is the one thing I wouldnt like to see in my application, and we are, after all, using Java, a OO language.
When we already have an ORM mapper that can be configured(forced would be the more precise word to use in this particular example) to process these thing itself, why to go programming it?
Also, we decided to user google Guice - its much faster, typesafe, and could significantly simplify our development/maintence/testing.

Spring and Hibernate, Lazy initiation problem

Hey I am developing an desktop application using Spring and Hibernate, and I have a problem with lazy initiation. I looked in the web and every solution is related to the open session in view pattern, but I can't use this pattern. I've also tried to get the sessionfactory from the HibernateTemplate, but it returns to me a disconnected session.
Does anyone know other solution?
I would suggest that you basically have two solutions:
Make arrangements to keep a Hibernate session open when you access a lazy-initialized object or collection. That means you're going to have to carefully mark your transaction boundaries in your code, a la the "open session in view" pattern. Spring makes this possible, but in a desktop application it won't be as straightforward as a web application where the transaction boundaries are a little more obvious.
Turn off all the lazy-initialization for your persisted objects in Hibernate.
Option 2 could lead to a lot of unnecessary database access, and option 1 means you have to seriously study your workflow and use cases.
Hope that helps!
One option is to call Hibernate.initialize() on the entities or collections to force initialize them. You'd want to do this before you return the data back to your view. I would consider this carefully, since it's going to generate a lot of SQL statements back to the database.
You may want to look into using "fetch" in your HQL queries or configuration the fetch mode to "eager" in your mappings (I believe it's FetchMode.EAGER in JPA or lazy="false" in hbm.xml).
#Jose: Don't manage the Session in your own ThreadLocal. Use SessionFactory.getCurrentSession() and configure Hibernate to use the "thread" SessionContext.
I had a very similar problem, and as I was not able to find any really appropriate solution to it. I came up with my own one combining a lot of different approaches found on the web and posted them to my blog.
Sorry, that I don't put it in all here, but it is to much work to do it over and over again in all the forums I found people having this or a similar problem
Remote Lazy Loading with Hibernate and Spring

Categories

Resources