0

I am working on spring boot 2.5 and Hibernate 5 but my getSession always comes as null. Below is the code I have. I have googled but the answers are for spring boot up to version 2.

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

and


import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ABC{
    
     @Autowired
        private EntityManager entityManager;

        private Session getSession() {
            //below line always return null/null pointer for me
            return entityManager.unwrap(Session.class);         
        }
    
    public String gettingSession() {        
        getSession();
        //I am trying to run queries like below after i get the session.
    //  List<EMP> employee=(List<EMP>) getSession().createQuery("from EMP").list();
        return "hello";
    }
}

I tried below links and getting same null/null pointer:

abhinav3414
  • 946
  • 3
  • 9
  • 31
  • (1) You need to show where you're calling these methods from. (2) You should use `@PersistenceContext` for an `EntityManager`, not `@Autowired`. (3) Use the JPA interfaces rather than the legacy Hibernate interfaces. (4) Just use Spring Data; this entire class can be replaced with an empty interface declaration. – chrylis -cautiouslyoptimistic- Aug 05 '21 at 07:30
  • If changing the annotation as chrylis suggested doesn't work, then we have to question if you're creating the object using `new ABC()` or injecting it via spring-boot. If it's the first way, then of course the entityManager is null, because you're not invoking the mechanisms that fill it. Secondly you really shouldn't be using the `Session` interface. Use `EntityManager` as it is more reliable for future compatibility. – coladict Aug 05 '21 at 07:40
  • As chrylis suggested by using @PersistenceContext issue got resolved. Thanks. – Imperial Aug 09 '21 at 12:00

0 Answers0