Application is based on Spring 2.5.5 and hibernate 3.2.0 GA.
I have the following method in my DAO that gets MessageEntities attached to the specified User:
public MessageEntity findByUserId(int userId) {
List<MessageEntity> result = (List<MessageEntity>) em.createNamedQuery(MessageEntity.Q_BY_USER_ID).setParameter("userId", userId).getResultList();
if (!result.isEmpty()) {
return result.get(0);
} else {
return null;
}
}
I need to call this method from my integration test to check whether system's behaviour is valid. As long as this method is not transactional, all I get is org.hibernate.SessionException: Session is closed!. The easiest way to avoid this is to mark findByUserId method with #Transactional(readOnly = true). But as I understand, transaction management should be the duty of service tier to avoid unnecessary transactions creation. So, my question is: how can I properly get away from SessionException?
You need to perform all your database actions within a transaction scope. As you identified its usually considered good design to let the service layer of your database model deal with transactions. The only constraint then becomes that you must invoke your service model to get within the transaction scope, which might be undesirable during test.
I would recommend to make use of the testing fascilites provided by spring. See 9.3.2.3 Transaction management
You could also manually create a transaction before testing your method, e.g., by
Session sess = factory.openSession();
Transaction tx = null;
// try catch
tx = sess.beginTransaction();
findByUserId(userId);
tx.commit();
tx.rollBack();
Put the following annotations on the top of your test class.
#RunWith(SpringJUnit4ClassRunner.class)
#Transactional
#ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml")
Also I wouldn't worry about putting additional #Transactional in DAOs.
Spring usually checks to see if you are already in a transaction (with in the same thread) before it creates another.
"But as I understand, transaction
management should be the duty of
service tier to avoid unnecessary
transactions creation."
This is more of a design choice (Spring Roo for example violates this)
You can use this annotation on your controller method:
#Transactional(readOnly = true)
Related
I am using following code
TestDAO {
Session session = null;
public TestDAO() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
//...more code create,update ...
//each method starts a transcation using "tx= session.beginTransaction();"
}
1)Now should i commit the transcation using tx.commit for a fetch operation too or only for save/update operation??
2)Should i create a seperate instance of TestDAO every time i need?Or should i create a singleton class that returns a single instance of DAO everytme?Will this have a problem?
You don't need tx.commit() for fetch operation. That is only needed for any save, update or delete. Close the session after data fetching.
If your application connect to only one database then use of single DAO is better. Spring framework encourages this. You will find more details about this on the following link
Don't repeat the DAO!
Transactions should not be the responsibility of the DAO, those really need to be controlled at a higher level. A DAO should be something that does queries and updates without being aware of the bigger picture, calls to DAOs can be grouped within an object like a Spring service or EJB session bean which is responsible for deciding what needs to go together in a transaction. This makes your DAO code more reusable since it doesn't have to know as much about the context in which it's operating.
Look at how Spring does it (in the sample applications like petstore that come with Spring), or better, look at the King/Bauer Hibernate-JPA book, which has a chapter on creating DAOs.
I was going through the hibernate tutorial and noticed that in every dao you have to get session,begin transaction.Perform all operations and then commit
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//Perform operations...
session.getTransaction().commit();
}
Then i have noticed in a framework called Appfuse which uses hibernate have dao methods as shown below.I dont see the begintransaction and commit
public List<Person> findByLastName(String lastName) {
//begintransaction
return getHibernateTemplate().find("from Person where lastName=?", lastName);
//Commit
}
I wonder how appfuse is wrapping up the dao operations with session.beginTransaction() and session.getTransaction().commit();
By using this technique the programmer doesn't have to bother about hibernate transaction stuff.I want it in such a a way that even if dao methods are overridden the transaction wrapper code should automatically come.
I have tried passing dao to a decorator class and wrapping the dao method call inside decorator class.But since the dao interface methods will change,the idea dint worked.How exactly we can achieve this.
I don't know how AppFuse is doing it, but a very common way of introducing transaction management into the service layer of an application is by using Aspect Oriented Programming. If you're using the Spring Framework, this (from the manual) is a good reference.
HibernateTemplate is part of Spring. You can read more about it at this link. But starting with Spring 3.0, it's considered to be deprecated in favor of declarative transaction management.
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.
I'll try to describe the situation. We have a web service; on each request web service starts a JTA transaction. It performs several database calls through XA datasource within that and calls some other web services (out of transaction context) and also makes a couple of remote EJB calls on other server.
The problem is that container seems to try to involve EJB into transaction (and that seems logical), but in fact I want it to not particpate in that transaction as when it does participate in that transcation it always times out in the final commit phase, but when I exclude EJB call it works fine.
I cann't change EJB implementation and only control web service code. So, my question is: how do I make an EJB call to transaction-aware EJB, but out of my JTA transaction, but still being in JTA transaction for other XA resourse? I hope I made my question clear :).
EDIT: Trying to make it more clear with pseudo-code example:
// Begin transaction
UserTransaction tx = (UserTransaction) ctx.lookup(USER_TRANSACTION);
tx.begin();
// Do some database operations on XA datasource
// Call remote EJB which has transcation attribute set to 'Supports'
AccountInfo account = accountEjb.getAccountInfo(userId, accountId); // <-- Is it possible to make this to be not be part of user transction?
// Do some more database operations on XA datasource
// Commit transaction
tx.commit();
You can create another bean with some appropriate transaction attribute. This bean can delegate all calls to the first bean.
Or you can invoke this ejb from another thread.
EJB transaction is declarative: for a given deployment of a given EJB, you specify its transaction semantics. The exact EJB can be deployed (under a different name, of course) and you can specify different requirements for that deployment. This is assuming that (a) you at least have the jar for the ejb, and, (b) that the ejb in question is stand alone and doesn't have dependencies on other components, and (c) the developer of the ejb hasn't violated the idea of the declarative transactions and his bean works outside of a transaction context as well.
You can create another method with the suitable tx attribute and then call it with through the self-injected proxy (pseudo-code):
#Stateless
public class LocalEJB1 {
#EJB
private LocalEJB1 localEJB1;
#EJB
private AccountEJB accountEjb;
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public AccountInfo callNonTx() {
return accountEjb.getAccountInfo(userId, accountId);
}
public void yourCurrentMethod() {
// Begin transaction
UserTransaction tx = (UserTransaction) ctx.lookup(USER_TRANSACTION);
tx.begin();
AccountInfo account = localEJB1.callNonTx();
// Do some more database operations on XA datasource
// Commit transaction
tx.commit();
}
}
I run following working code:
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
String id = (String) FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get(
"storeId");
Transaction t = session.beginTransaction();
stores = getStores();
for (Store store : stores) {
if (store.getId() == Integer.parseInt(id)) {
session.delete(store);
}
}
t.commit();
} catch (Exception e) {
} finally {
session.close();
}
}
When i try redo this code to use Hibernate template, i go unending request to DB:
HibernateTemplate template = new HibernateTemplate();
template .setSessionFactory(sessionFactory);
stores = template.find("from Stores");
for (Store store : stores) {
if (store.getId() == Integer.parseInt(id)) {
template.delete(store);
}}
Looks like transaction is not closed.
How could I close transaction this case? And is it will better at all to use Hibernate template approach instead of session approach showed at first code?
You didn't say it, but I assume you're referring to the HibernateTemplate class in the Spring Framework. HibernateTemplate participates in Spring transactions, but it doesn't manage them on its own. Spring provides a lot of ways to manage transactions both programmatically and declaratively. If you're just experimenting, you can use the TransactionTemplate class to quickly test it out. For larger projects, you should consider using declarative transaction management because it simplifies your code, although it's a little trickier to set up initially.
As for whether or not the HibernateTemplate approach is better than managing your sessions manually, I'd say anything that reduces boilerplate code is a good thing, so yes. This is especially crucial on big projects. However, depending on your project, HibernateTemplate might not even be necessary. It was originally created to work around some deficiencies in Hibernate 2.x, but many of those deficiencies were eliminated in Hibernate 3. So before adopting it, read the HibernateTemplate JavaDoc for a discussion of the advantages.