Topic: 如何用junit测试没有手工维护事务的 hibernate 代码

  Print this page

1.如何用junit测试没有手工维护事务的 hibernate 代码 Copy to clipboard
Posted by: worldcreatxr
Posted on: 2005-03-15 13:54

如何用junit测试没有手工维护事务的 hibernate 代码

下面这段代码看上去,或运行时都正常,似乎已经把数据写入数据库了。

可是事实上没有

========================================
public void testSaveOrUpdate() {
try {
PigeonholeType pigeonholeType = new PigeonholeType();
pigeonholeType.setSymbol("none");
PigeonholeRule pigeonholeRule = new PigeonholeRule();
pigeonholeRule.setXtypeSymbol("SB006");
pigeonholeRule.setSize(new Integer(456));
pigeonholeRule.setPigeonholeType(pigeonholeType);
pigeonholeRuleDao.saveOrUpdate(pigeonholeRule);

} catch (Exception e) {
e.printStackTrace();
}

PigeonholeRule obj = pigeonholeRuleDao.loadByPrimaryKey("SB006");
System.out.println(obj.getSize()); 读数据

Xtype xtype = xtypeDao.loadByPrimaryKey("SB006");
Iterator it = xtype.getSetOfPigeonholeRule().iterator();
while (it.hasNext()) {
PigeonholeRule pigeonholeRule = (PigeonholeRule)it.next();
System.out.println(pigeonholeRule.getPigeonholeType().getSymbol());
System.out.println(pigeonholeRule.getPigeonholeType().getTitle());
}
}

}

=========================================

public Serializable saveOrUpdate(PigeonholeRule obj)
throws DataAccessException {
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
// tx = session.beginTransaction();
session.saveOrUpdateCopy(obj);
session.flush();
// if not use transaction tx.commit();  这里不手工维护事务
return obj;
} catch (HibernateException he) {
try {
tx.rollback();
} catch(HibernateException hex) {
throw SessionFactoryUtils.convertHibernateAccessException(hex);
}

throw SessionFactoryUtils.convertHibernateAccessException(he);
} finally {
SessionFactoryUtils
.closeSessionIfNecessary(session, sessionFactory);
}
}

2.Re:如何用junit测试没有手工维护事务的 hibernate 代码 [Re: worldcreatxr] Copy to clipboard
Posted by: wuliang
Posted on: 2005-03-24 11:14

以前碰过,现在记不清了~:)

public static Session openSession() throws HibernateException {
Session se = getSF().openSession();
try {
//缺省openSession得到的是autocommit=false的连接
se.connection().setAutoCommit(true);
} catch (Exception e) {
e.printStackTrace();
}
return se;
}

public static void closeSession(Session se) {
try {
if (se != null) {
se.close();
}
} catch (HibernateException e) {
e.printStackTrace();
}
}

印象里autocommit=false时,一定要自己调用commit(),否则不会保存,但做测试时,不清楚是什么原因(可能是缓存etc),能够查到最新数据,产生已保存的错觉。这个问题后来是跟踪源代码才搞清的,

不管怎样,感觉这样的测试没有必要,因为这是测试hibernate,不是测自己的业务代码

如果确实需要对hibernate测试,也应该用其他查询工具来验证,如jdbc


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923