【问题标题】:hibernate configuration for testing -(newbie wows)用于测试的休眠配置-(新手哇)
【发布时间】: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


    【解决方案1】:

    我非常想使用带有测试数据库属性的 ​​test_hibernate.cfg.xml,但由于配置是在 HibernateUtil 的静态块中完成的

    所以不要在静态块中创建配置。

    相反,创建一个类,该类接受配置文件路径的参数(例如 Spring 的 LocalSessionFactoryBean),该文件返回要使用的 Configuration/SessionFactory。或者,如果您真的想坚持使用HibernateUtil(在任何生产环境中都强烈建议不要使用这种策略),请将其更改为读取属性或系统环境变量以读取配置。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 2014-02-11
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2015-07-28
      • 2016-05-06
      • 2018-10-21
      • 2012-11-19
      相关资源
      最近更新 更多