springBoot获取Jpa的SessionFactory

项目中对于复杂的SQL查询,需要自己拼接SQL语句,然后利用hibernate的sessionFactory去构建查询.

先说下maven依赖,用到的是springboot 2.1.0.RELEASE版本以及spring-boot-starter-data-jpa,其中spring-boot-starter-data-jpa底层已经依赖了hibernate-core5.3.7.Final

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

在这里插入图片描述

因此刚开始我以为获取hibernate的sessionFactory就能操作数据库,所以配置了以下代码

    @Bean
    public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf){
        return emf.unwrap(SessionFactory.class);
    }

或者是(这种会显示HibernateJpaSessionFactoryBean 已经过期,可能hibernate版本太高了)

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
        }

然后在service层配置

@Autowired
private SessionFactory sessionFactory

就能在方法中通过sessionFactory.getCurrentSession()或sessionFactory.openSession()去操作SQL语句获取查询结果了,结果发现报类似于这样的错误

***************************
APPLICATION FAILED TO START
***************************

Description:

Field session in xx.dao.xxxDaoImpl required a bean of type 'org.hibernate.SessionFactory' that could not be found.


Action:

Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.

或者这样的错

Consider defining a bean named ‘entityManagerFactory’ in your configuration

网上搜索一番,有说hibernate依赖版本冲突的,有说配置不正确,该试的办法都试过了,还是不能解决.

最后解决方法,直接在service层配置

    @PersistenceContext
    private EntityManager entityManger;

然后利用EntityManager 的接口方法去操作数据库。
例子:

   @PersistenceContext
    private EntityManager entityManger;

    @Test
    public void contextLoads() {

        List resultList = entityManger.createNativeQuery("select * from t_article_category").getResultList();
        System.out.println("长度:"+resultList.size());

    }

附:
JPA使用EntityManagerFactory开闭session,而Hibernate使用SessionFactory开闭session。两者区别:

  1. EntityManagerFactory是JPA的标准API,如果使用EntityManagerFactory,在更换实现JPA的ORM框架时,需要改动的代码很少。如果使用SessionFactory,因为SessionFactory是Hibernate的,无法直接更换ORM框架,更换ORM的话,需要修改所有的代码。

  2. 如果想使用Hibernate的某些高级特性,只能使用SessionFactory,使用EntityManagerFactory无法享受Hibernate的高级用法。

猜你喜欢

转载自blog.csdn.net/u013068184/article/details/85279704