Spring Boot 和 Hibernate 的简单整合
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan("com.example.domain");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
@Bean
@Autowired
public PlatformTransactionManager hibernateTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
这段代码定义了一个配置类,用于创建LocalSessionFactoryBean
和HibernateTransactionManager
。LocalSessionFactoryBean
用于创建SessionFactory,它需要数据源和实体类的包路径。HibernateTransactionManager
用于管理事务,它需要SessionFactory作为参数。这段代码提供了Spring Boot和Hibernate整合的基本框架。
评论已关闭