Why HibernateTemplate isn't recommended? [duplicate] - java

This question already has answers here:
Why is HibernateDaoSupport not recommended?
(2 answers)
Closed 9 years ago.
I was used to getHibernateTemplate() in hibernate 3, and now I am moving to Hibernate 4 for and here I didn't find following class:
org.springframework.orm.hibernate4.support.HibernateDaoSupport;
And here I had read about it is not more recommended to use
http://forum.springsource.org/showthread.php?117227-Missing-Hibernate-Classes-Interfaces-in-spring-orm-3.1.0.RC1
Can someone explain me why? and in hibernate 4 will now I need to do all task like commiting, close, flushing the transaction which was automatically managed by getHibernateTemplate() method?

Because its main goal was to get a Hibernate session tied to the current Spring transaction, when SessionFactory.getCurrentSession() didn't exist. Since it now exists (and for a long time: HibenateTemplate usage is discouraged even in the hibernate3 package), there is no reason to use this Spring-specific class instead of using SessionFactory.getCurrentSession() to get a session tied to the current Spring transaction.
If you use Spring, then you should use its declarative transaction management, which allows you to avoid opening, committing, closing and flushing. It's all done by Spring automatically:
#Autowired
private SessionFactory sessionFactory;
#Transactional
public void someMethod() {
// get the session for the current transaction:
Session session = sessionFactory.getCurrentSession();
// do things with the session (queries, merges, persists, etc.)
}
In the above example, a transaction will be started (if not already started) before the method invocation; A session will be created by Spring for the transaction, and the session will be automatically flushed before the commit of the transaction, that will be done by Spring automatically when the method returns.

Related

Transaction rollback not working for multiple repositories for spring JPA

Both of my transaction does not rollback, maybe I am missing on some core concepts.
#Autowired
CustomRepositoryA customrepositoryA
#Autowired
CustomRepositoryB customrepositoryB
#Transactional
public void method(){
//businesslogic
//works fine
customrepositoryA.save(obj);
customrepositoryA.flush();
//Error
customrepositoryB.save(obj);
customrepositoryB.flush();
}
So my understanding is that the #Transactional annotation should rollback both the repository transactions if there is an error but it just rollbacks for the second one the first transaction is persisted into DB.
Also does JPA repository provide a way to clear out session caches after flush equivalent to session.clear() in hibernate?
Here is the link to the same problem I am facing asked a few years ago
One transaction for several JpaRepositories' methods

write good code for hibernate performance [duplicate]

This question already has answers here:
Hibernate Performance Best Practice?
(3 answers)
Closed 7 years ago.
I am facing some performace issue in my application. Especially while saving to and retrieving from the database.
My application is a standalone application. Not a webapplication. I am using hibernate for database communication.
This application has not gone in production. This application will be used 50 people simultaneously.
Here is the below code which I have used for getting session. I suspect below is the code for getting slowness.
public class HibernateUtil {
public Session getSession() {
SessionFactory buildSessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = buildSessionFactory.openSession();
return session;
}
public Transaction getTransaction() {
return getSession().getTransaction();
}
}
I am not sure how to write a good code for opening session.
Can anyone suggest how to refactor this code to a good code?
Also, are the session getting closed, means once the thread has completed a process, are we closing the session.
There is no single statement answer for your question unless the code is observed, there are lot of attributes on which the performance of the system depends.
1.) GC - When and which algorithm being used.
2.) How many session are getting opened, are there any sessions which are left idle. Long running sessions should be avoided.
3.) Introducing Caching mechanism in the code, Hibernate 2nd Level cache, query caching
4.) How big the objects are getting retrieved from the database.
5.) How many queries are getting fired into DB.
Please refer this, this
I faced the similar type of issue in past, the base culprit for this is your are creating the factory instance every time when you are trying to get a transaction.
Please use the singleton pattern to create the SessionFactory object, means just create Session factory once and get all the session instance from that factory object, I am pretty sure you will not face the performance issue after this change
change Something like below-
static SessionFactory buildSessionFactory;
public static getSessionFactory() {
if(buildSessionFactory==null) {
buildSessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
}
}
public Session getSession() {
getSessionFactory();
Session session = buildSessionFactory.openSession();
return session;
}
public Transaction getTransaction() {
return getSession().getTransaction();
}
It will solve your problem

Why can I insert/update data with hibernate even when there's no transaction involved?

As we all know that in Hibernate if no transaction commit, the changes won't affect in database. But I found something weird. And the code as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Model model = new Model();
...
session.save(model);
session.flush();
session.close();
And the model was saved to database even there's no transaction, anyone can explain this?
Any comments would be appreciated! Thanks!
PS: I am using mysql.
The session.flush command saved the transaction. If it's wrong, you should use transaction.
usually hibernate needs the line session.beginTransaction(); to work. You didn't write that and your application worked, I guess your application runs in an Application server, which provides transaction management. e.g. jboss, weblogic...
However it doesn't mean that there is no transaction. Did you set auto-commit true?
btw, session.flush() and txn.commit() are different.
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
After session.flush(), you still can call txn.rollback() to rollback all changes.
edit
oh I saw you used spring. did you configured txnmanager in spring?
Hibernate doesn't need transactions, the most common problems in database-based applications are just easier to solve with transactions which is why usually everyone uses transactions with Hibernate. But that's mere coincidence/convention/laziness.
All Hibernate needs is a java.sql.Connection and if your container provides one even though there is no current transaction manager configured, Hibernate is fine with that.
In fact, Hibernate has no idea that there might be a transaction manager. So session.flush() will use the ApplicationContext to get a connection, generate the SQL and use JDBC to send the generated SQL code to the database.
From Hibernate's point of view, that's all that happens.
There can be several reasons why the data is committed to the database:
You forgot to turn of auto commit on the connection.
Your web container / spring config automatically wires a transaction manager that synchronizes with HTTP requests.
Your code is called form another method which is annotated with #Transactional; in this case, you inherit the existing transaction.

"suspend" hibernate session managed by spring transaction manager

Is there any way to remove/suspend a current spring managed hibernate session from a thread so a new one can be used, to then place the original session back onto the thread? Both are working on the same datasource.
To describe the problem in more detail. I'm trying to create a plugin for a tool who has it's own spring hibernate transaction management. In this plugin I would like to do some of my own database stuff which is done on our own spring transaction manager. When I currently try to perform the database actions our transaction manager starts complaining about an incompatibly transactionmanager already being used
org.springframework.transaction.IllegalTransactionStateException: Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access.
A workaround that seems to do the trick is running my own code in a different thread and waiting for it to complete before I continue with the rest of the code.
Is there a better way then that, seems a bit stupid/overkill? Some way to suspend the current hibernate session, then open a new one and afterworths restoring the original session.
Is there any reason you can't have the current transaction manager injected into your plugin code? Two tx managers sounds like too many cooks in the kitchen. If you have it injected, then you should be able to require a new session before doing your work using the #transactional annotation's propagation REQUIRES_NEW attribute see the documentation for an example set-up
e.g.
#transactional(propogation = Propogation.REQUIRES_NEW)
public void addXXX(Some class) {
...
}
But this would use spring's PlatformTransactionManager rather than leaving it up to hibernate to manage the session / transaction.

HibernateDaoSupport , transaction is not rolled back

I'm playing around with Spring + Hibernate and some "manual" transaction management with PostgreSQL
I'd like to try this out and understand how this works before moving to aop based transaction management.
#Repository
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
#Override
public void saveUser(User u) {
Transaction tx = getSession().beginTransaction();
getHibernateTemplate().saveOrUpdate(u);
tx.rollback();
}
}
Calling saveUser here, I'd assume that saving a new User will be rolled back.
However, moving to a psql command line, the user is saved in the table.
Why isn't this rolled back, What do I have to configure to do transactions this way ?
Edit; a bit more debugging seems to indicate getHibernateTemplate() uses a different session than what getSession() returns (?)
Changing the code to
Transaction tx = getSession().beginTransaction();
getSession().persist(u);
tx.rollback();
and the transaction does get rolled back. But I still don't get why the hibernateTemplate would use/create a new session..
A couple of possibilities spring to mind (no pun intended):
a) Your JDBC driver defaults to autocommit=true and is somehow ignoring the beginTransaction() and rollback() calls;
b) If you're using Spring 3, I believe that SessionFactory.getSession() returns the Hibernate Session object wrapped by a Spring proxy. The Spring proxy is set up on the Session in part to handle transaction management, and maybe it's possible that it is interfering with your manual transaction calls?
While you can certainly use AOP-scoped proxies for transaction management, why not use the #Transactional(readOnly=false|true) annotation on your service layer methods? In your Spring config file for your service layer methods, all you need to do to make this work is to add
<tx:annotation-driven />
See chapters 10 and 13 of the Spring Reference Documentation on Transaction Management and ORM Data Access, respectively:
http://static.springsource.org/spring/docs/3.0.x/reference/index.html
Finally, if you're using Spring 3, you can eliminate references to the Spring Framework in your code by injecting the Spring-proxied SessionFactory bean into your DAO code - no more need to use HibernateDaoSupport. Just inject the SessionFactory, get the current Session, and use Hibernate according to the Hibernate examples. (You can combine both HibernateDaoSupport and plain SessionFactory-based Hibernate code in the same application, if required.)
If you see the JavaDoc for HibernateDaoSupport.getSession() it says it will obtain a new session or give you the one that is used by the existing transaction. In your case there isn't a transaction listed with HibernateDaoSupport already.
So if you use getHibernateTemplate().getSession() instead of just getSession(), you should get the session that is used by HibernateTemplate and then the above should work.
Please let me know how it goes.
EDIT:
I agree its protected...my bad. So the other option then is to keep the session thread bound which is usually the best practice in a web application. If HibernateDaoSupport is going to find a thread bound session then it will not create a new one and use the same one. That should let you do rollbacks.

Categories

Resources