Hibernate 4.3, when building SessionFactory why do we have to supply the properties twice?

☆樱花仙子☆ 提交于 2019-12-10 10:49:17

问题


Using the Hibernate 4.3.5 when you want to create a SessionFactory (e.g. unit testing) you will have to supply the properties twice:

  1. Once for configuration
  2. Second time, when applying settings to the service registry builder

The example looks like:

Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
properties.put("hibernate.connection.url", "jdbc:hsqldb:mem:test");
properties.put("hibernate.connection.username", "sa");
properties.put("hibernate.connection.password", "");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", "true");

SessionFactory sessionFactory = new Configuration()
    .addProperties(properties)
    .addAnnotatedClass(SecurityId.class)
    .buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
);  

If I comment:

//.addProperties(properties)

Then the "hibernate.hbm2ddl.auto" property doesn't get thorough:

Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: SECURITYID

If I comment:

//.applySettings(properties)

I the get:

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set 

Coda available on GitHub.


回答1:


Try the following code, it uses properties from configuration.

Configuration configuration = new Configuration();
configuration.addAnnotatedClass(SecurityId.class);
configuration.addProperties(properties);
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);


来源:https://stackoverflow.com/questions/24016319/hibernate-4-3-when-building-sessionfactory-why-do-we-have-to-supply-the-propert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!