【发布时间】:2011-08-02 21:18:11
【问题描述】:
几个月来,我一直在学习使用休眠。 我发现很难决定如何配置 hibernate 以在测试数据库上工作。
我有一个 hibernate.cfg.xml,其中 db 参数作为 元素给出。
<property name="connection.url">
jdbc:postgresql://localhost/mydb
</property>
<property name="connection.username">me</property>
<property name="connection.password">mypasswd</property>
我的网络应用使用 HibernateUtil 类,它加载如下配置
class HibernateUtil {
private Class<T> persistentClass;
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
...
我的dao实现使用上面的类来获取Session
public class BaseDaoImpl<T, ID extends Serializable>{
private Session session;
...
public Session getSession() {
if (session == null || !session.isOpen()){
return HibernateUtil.getCurrentSession();
}else{
return session;
}
}
public T findById(ID id){
T entity = (T) getSession().load(getPersistentClass(), id);
return entity;
}
只要我在 cfg.xml 文件中配置的 mydb 上工作就可以了。但是对于我的测试,我使用的是 test.properties 文件中给出的另一个数据库
test.db.url=jdbc:postgresql://localhost/mytestdb
test.db.driver=org.postgresql.Driver
test.db.username=testme
test.db.password=testpass
我可以让 hibernate 在 mytestdb 上工作的唯一方法是手动替换 cfg.xml 中的每个 db 相关属性。我非常希望将 test_hibernate.cfg.xml 与测试 db 属性一起使用,但是由于配置已完成在 HibernateUtil 的静态块中,这是行不通的。
有没有更好的方法为这两个数据库配置休眠? 我正在使用 ant 作为构建工具..
欢迎任何建议
吉姆
【问题讨论】:
标签: java hibernate testing configure