java - 用于测试的 hibernate 配置 -(新手哇)

标签 java hibernate testing configure

我已经学习使用 hibernate 几个月了。 我发现很难决定如何配置 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 中每个与数据库相关的属性。我非常想将 test_hibernate.cfg.xml 与测试数据库属性一起使用,但由于配置已完成在 HibernateUtil 的静态 block 中,那是行不通的。

有没有更好的方法为这两个数据库配置 hibernate ? 我正在使用 ant 作为构建工具..

欢迎大家提出建议

吉姆

最佳答案

I would very much like to use test_hibernate.cfg.xml with the test db properties,but since the configuration is done in a static block in HibernateUtil

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

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

关于java - 用于测试的 hibernate 配置 -(新手哇),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6912338/

相关文章:

spring - 使用 EntityManager (JPA) 的 DAO 中 update () 方法的推荐行为?

html - 在移动浏览器上测试 WML

java - 如何将表单字段放入列表中以便能够迭代它们?

java - 什么是正确的正则表达式?

java - Weblogic 12c 无法解析类文件 hikaricp-3.4.5 module-info.class

python - py.test 将消息和测试结果/断言记录到一个文件中

Java:在嵌入式 Tomcat 上测试 Web 应用程序(Tomcat 无法启动)

Java读取和编码大型二进制文件

java - 我的 selenium 中打开了两个 Firefox 浏览器窗口

java - 使用 Hibernate Validator 在错误消息中包含字段名称