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:
- Once for configuration
- 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.
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