我正在尝试在没有xml的情况下配置Spring和Hibernate。这是我的SessionFactory bean。当我向配置中添加带注释的类时 - 它可以正常工作。我想自动执行,但添加一个包到配置没有帮助由于某种原因,我得到“识别器未映射”错误
@Bean
public SessionFactory sessionFactory(){
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.connection.driver_class",ds_driver);
hibernateProperties.put("hibernate.connection.url",ds_url);
hibernateProperties.put("hibernate.connection.username",ds_username);
hibernateProperties.put("hibernate.connection.password",ds_password);
hibernateProperties.put("hibernate.show_sql", false);
hibernateProperties.put("connection.pool_size", 1);
hibernateProperties.put("current_session_context_class", "thread");
hibernateProperties.put("hibernate.hbm2ddl.auto", "update");
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
configuration.addPackage("app.entity"); // **doesnt work**
configuration.addAnnotatedClass(Identificator.class); // **works fine**
configuration.addProperties(hibernateProperties);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
答案 0 :(得分:0)
#addPackage()
方法读取包级别元数据,而不读取包中的类。不幸的是,Configuration
类没有提供您想要的方法,您必须将所有类传递给#addAnnotatedClass()
。
一种可能的(但不确定是否可推荐)解决方案是使用另一种解决方案来查找所需的类描述符,从中构建一个列表,然后将它们循环传递给#addAnnotatedClass()
。我很确定,Spring有解决方案。
答案 1 :(得分:0)
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration()
.configure(getMappedValue("Universal", "qb_hibernate"))
.setProperty("hibernate.connection.autocommit", "true")
.setProperty("connection.pool_size", "20000")
.setProperty("hibernate.dialect", getMappedValue("Universal", "dialect"))
.setProperty("hibernate.connection.driver_class", getMappedValue("Universal", "driver_class"))
.setProperty("hibernate.connection.url", getMappedValue("Universal", "url"))
.setProperty("hibernate.connection.username", getMappedValue("Universal", "userName"))
.setProperty("hibernate.connection.password", getMappedValue("Universal", "password"))
.setProperty("hibernate.show_sql", "false")
.setProperty("hibernate.current_session_context_class", "thread")
.setProperty("hibernate.query.factory_class", "org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory");
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
LocalSessionFactoryBuilder builder
= new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("zw.co.techno.xxxxx.model").buildSettings(serviceRegistry);
// builds a session factory from the service registry
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
sessionFactory = builder.buildSessionFactory();
}
return sessionFactory;
}