Hibernate还是比较常用的,于是我研究了一下Hibernate单元测试,在这里拿出来和大家分享一下,希望对大家有用。
本文介绍在Hibernate单元测试中最重要的就是要保持测试实例是独立的。因为该方法仍然涉及数据库,所以需要一种方法在每个Hibernate单元测试实例之前清理数据库。在我的数据库架构中有四个表,所以我在TestSchemaz上编写了reset()方法,该方法从使用JDBC的表中删除所有行。注意,因为HSQLDB能识别外键,删除表的顺序是很重要的,下面是代码:
public static void reset() throws SchemaException {
Session session = HibernateUtil.getSession();
try {
Connection connection = session.connection();
try {
Statement statement = connection.createStatement();
try {
statement.executeUpdate("delete from Batting");
statement.executeUpdate("delete from Fielding");
statement.executeUpdate("delete from Pitching");
statement.executeUpdate("delete from Player");
connection.commit();
}
finally {
statement.close();
}
}
catch (HibernateException e) {
connection.rollback();
throw new SchemaException(e);
}
catch (SQLException e) {
connection.rollback();
throw new SchemaException(e);
}
}
catch (SQLException e) {
throw new SchemaException(e);
}
finally {
session.close();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
当确定在Hibernate 3.0中进行大量删除操作时,应该能从应用程序中删除直接JDBC的***一位。到此时为止,必须获取数据库连接并向数据库直接提交SQL。在确保没有关闭连接的情况下,为了释放资源,只关闭会话就足够了。出于手工编写许多JCBC代码来进行开发的习惯,***个版本关闭了JDBC连接。因为通过配置Hibernate创建的连接池只带有一个链接,在***个之后就完全破坏了测试。一定要注意这种情况!既然在测试类运行时(设想运行所有的测试实例)不能确定数据库的状态,应该在setUp()方法中包含数据库清除,如下所示:
public void setUp() throws Exception {
TestSchema.reset();
}
- 1.
- 2.
- 3.
【编辑推荐】