开发者

Working with JDBC in EJB-Hibernate env

I have a little of confusion about JDBC connection, transactions and their integration in EJB, JTA, Hibernate environment. My doubts are:

  1. when we use @Resource DataSource ds; ... ds.getConnection() , are we working in the same transaction used by the managed bean? Should we close the connection, statement, resultset?

  2. what about session.doWork? Are we in the same transaction? What about closing statement and result set?

  3. aggressive release mode in Hibernate means that开发者_开发知识库 connections are closed after each statement. Does it mean that transaction is committed too? (I don't think this is true, but I can't understand how Hibernate works here)


There are a few things you need to figure out. First thing you need to identify what is your unit of work. The session-per-request pattern is one of the most used and unless you have specific needs stick with that. If you are using Hibernate you don't use statements and result sets directly. Hibernate will do that for you. what you need to close is the hibernate session

What you use is a SessionFactory and a Session object. The session pretty much represents your unit of work. Inside the hibernate session you get your objects, you change them and save them back. The session per request pattern opens a session when a request is received and closes it when the response is sent back.

In a container managed EJB session bean a transaction is available and the datasource you (or hibernate) use in such a container is automatically handled by a JTA TransactionManager.

Now because Hibernate is smart it can automatically bind the "current" Session to the current JTA transaction. This enables an easy implementation of the session-per-request strategy with the getCurrentSession() method on your SessionFactory:

try {
    UserTransaction tx = (UserTransaction)new InitialContext()
                            .lookup("java:comp/UserTransaction");

    tx.begin();

    // Do some work
    factory.getCurrentSession().load(...);
    factory.getCurrentSession().persist(...);

    tx.commit();
}
catch (RuntimeException e) {
    tx.rollback();
    throw e; // or display error message
}

So to answer your questions:

If you are using Hibernate with JTA in a container you'd be better off using a JPA EntityManager or maybe spring hibernate template.

Here are some references: http://community.jboss.org/wiki/sessionsandtransactions#Transaction_demarcation_with_JTA http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/HibernateTemplate.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜