ernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:myorcl
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.username">abc</property>
<property name="connection.password">abc</property>
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="com/cts/testhb/model/TUser.hbm.xml" />
</session-factory>
</hibernate-configuration>
然后上述代码将变成如下的样子:
public void testUser() throws Exception {
Transaction tran = null;
SessionFactory factory = null;
UserDAO userDAO = new UserDAOImpl();
try {
factory = HibernateUtil.getInstance().getSessionFactory();
Session session = factory.getCurrentSession();
tran = session.beginTransaction();
for (int i = 0; i < 100; i++) {
TUser testUser = new TUser();
testUser.setId(new Integer(i));
testUser.setName("abc");
userDAO.addUser(testUser);
}
tran.commit();
} catch (Exception e) {
tran.rollback();
throw new Exception(e);
} finally {
ThreadLocalSessionContext.unbind(factory);
}
}
而你的每个DAO方法中的代码是这样实现的:
public void addUser(TUser user) throws Exception {
SessionFactory factory = HibernateUtil.getInstance()
.getSessionFactory();
Session session = factory.getCurrentSession();
session.save(user);
}
是不是很方便的哈。
3.1.3 openSession与getCurrentSession的区别
严重注意下面3点:
- openSession一旦被调用,必须且一定要在finally块中close,要不然你就等着out of memory吧;
- 如果你使用的是getCurrentSession,那么你不能在finally块中调用”session.close()”,不行你可以在finally块中用try-catch把session.close();包起来,然后在catch{}块中抛出这个exception,这个exception将会是:sessionhas been already closed。
因为:
l 如果你用的是getCurrentSession,那么它在session.commit()或者是session.rollback()时就已经调用了一次session.close()了,因此你只要正确放置session.commit()与rollback()即可。
l 你必须在finally块中调用”ThreadLocalSessionContext.unbind(factory);”,以使得当前的事务结束时把session(即dbconnection)还回db connection pool中
² 如果你使用的是getCurrentSession,那么就算你是一个简单的select语句,也必须包含在:
tran = session.beginTransaction();
//your select hibernate query
tran.commit();
这样的事务块中,要不然它将会抛出这样的一个错误:
NoHibernate Session bound to thread, and configuration does not allow creation ofnon-transactional
看下面的例子:
try {
factory = HibernateUtil.getInstance().getSessionFactory();
Session session = factory.getCurrentSession();
tran = session.beginTransaction();
TUser testUser = userDAO.getUserByID("1");
log.info("user id===="+testUser.getId()+" user name===="+testUser.getName());
tran.commit();
} catch (Excep