由于您使用的是Spring
Boot,因此应该对数据库配置使用不使用XML的配置。spring启动与Hibernate,您需要创建整合
LocalSessionFactoryBean,
DataSource,
HibernateTransactionManager和
PersistenceExceptionTranslationPostProcessor豆是这样的:
@Configurationpublic class DatabaseConfig { @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan("com.example.model"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://localhost:5432/testdb"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } Properties hibernateProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.ddl-auto", "update"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); return properties; }}
在上面的数据库配置中,我使用了postgreSQL数据库。
要获得sessionFactory自动装配
SessionFactory接口的实例,如下所示:
@Autowired SessionFactory sessionFactory;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)