Java 创建名为“的bean”时出错;“sessionFactory”;
嗨,我是春季和冬眠的初学者,如果这个问题是初级的,我很抱歉。我正在使用Spring4.3.4、Hibernate5.0.3和MySQL。我明白了: 这是我的hibernate.propertiesJava 创建名为“的bean”时出错;“sessionFactory”;,java,mysql,spring,hibernate,Java,Mysql,Spring,Hibernate,嗨,我是春季和冬眠的初学者,如果这个问题是初级的,我很抱歉。我正在使用Spring4.3.4、Hibernate5.0.3和MySQL。我明白了: 这是我的hibernate.properties # jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/english?createDatabaseIfNotExist=true jdbc.user=user jdbc.pass
# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/english?createDatabaseIfNotExist=true
jdbc.user=user
jdbc.pass=pass
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update
异常是由以下事实引起的:环境不具有此类属性,并且语句
env.getProperty(…)
返回null,无法将其设置为值
确保Spring加载了您的
hibernate.properties
文件。或者将此属性移动到应用程序.properties
文件。您的回答对我很有帮助。非常感谢你。我刚刚添加了@PropertySource(value={“classpath:hibernate.properties”}),问题就消失了
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Autowired
Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() throws PropertyVetoException {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan("english.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public ComboPooledDataSource restDataSource() throws PropertyVetoException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager txManager
= new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers",
"true");
}
};
}
}
# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/english?createDatabaseIfNotExist=true
jdbc.user=user
jdbc.pass=pass
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update