简体   繁体   中英

Spring Boot 2.0.x EntityManagerFactory Null

I am trying to use Hibernate SessionFactory to get data from Mysql and tried to unwrap SessionFactory from EntityManagerFactory.

This code is perfectly working fine in Spring boot 1.5.x but not in 2.0.x

@Configuration
public class SessionFactoryConfig {

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public SessionFactory getSessionFactory() {
    if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
        throw new NullPointerException("Factory is not a hibernate factory");
    }
    return entityManagerFactory.unwrap(SessionFactory.class);
 }
}

Can anyone please help me to fix this issue? Any help would be highly appriciated. Thank you!

As @m-deinum pointed out in the comment, if you really want to use the SessionFactory you can avoid creating the SessionFactory and use an injected EntityManager instance to access it directly in your repository object.

For example:

@Repository
public class MyRepository {
    @Autowired
    private EntityManagerFactory emf;

    public void saveEntity(Foo foo) {
        emf.unwrap(SessionFactory.class).getCurrentSession().saveOrUpdate(foo);
    }

    @Override
    public Foo getEntity(Integer id) {
        return emf.unwrap(SessionFactory.class).getCurrentSession().get(Foo.class, id);
    }
}

Hope that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM