【SpringBoot学习三】springboot2+hibernate5

springboot2集成hibernate5,先准备一个数据库及java驱动,我用的是mysql。
集成步骤如下

1.pom配置

需要的包如下,hibernate、spring事务、连接池、ORM、数据库驱动


    org.hibernate
    hibernate-entitymanager
    5.2.17.Final


    org.springframework
    spring-tx
    5.0.5.RELEASE


    commons-dbcp
    commons-dbcp
    1.4


    org.springframework
    spring-orm
    5.0.5.RELEASE


    mysql
    mysql-connector-java
    5.1.46

2.hibernate配置类

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.bootplus" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfig {

    @Autowired
    private Environment environment;
    //session factory
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.bootplus.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }
    // 数据源配置
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
    //获取hibernate配置
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }
    // 事务管理
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sf) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(sf);
       return txManager;
    }
}

3.启动类中引入hibernate配置

@Configuration
@EnableAutoConfiguration(exclude=HibernateJpaAutoConfiguration.class)
//java.lang.ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder
@ComponentScan
@SpringBootApplication
@EnableCaching
public class Application extends SpringBootServletInitializer {


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
        return builder.sources(Application.class);
    }

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

}
@EnableAutoConfiguration(exclude=HibernateJpaAutoConfiguration.class)

这个地方如果不加exclude会报错
java.lang.ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

4.hibernate配置

在application.properties属性文件中加入hibernate及数据库链接配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
jdbc.username=root
jdbc.password=123456
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.format_sql=false

数据库配置就不多介绍了,自己的数据库链接串配置好,数据库链接的用户名,密码配置好,至此springboot集成hibernate就大功告成了。

5.使用

public class DaoImpl {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }
    //样例代码,具体实现自己封装,可以将常用的操作自行封装方便使用
    private Query createQuery(String queryString, Object… values) {
        //断言,hql语句不能为空
        Assert.hasText(queryString, "没有发现HQL语句");
        //创建查询
        Query queryObject = getSession().createQuery(queryString);
        if (values != null) {//参数赋值
            for (int i = 0; i < values.length; i++) {
                queryObject.setParameter(i, values[i]);
            }
        }
        return queryObject;//返回查询的对象
    }
}

6.事务处理

@Service
@Transactional//在service上面加上这个注解即可,或者在你需要事务的类上加这个注解
public class AuthService extends ServiceImpl{}

至此springboot集成hibernate就完成了,万事开头难,后面还需要将操作方法封装一下就更清晰简洁了。

你可能感兴趣的:(SpringBoot学习)