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

Viewed 14964

I am new to JavaEE and i have been working on a simlpe Springboot project. Each time i run it i get this error:

Please feel free to answer to my question and any improvemnet in the code is Highly Appreciate.

Field sessionFactory in com.example.dao.CartDaoImpl 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.
5 Answers

Create service and use it to get session from EntityManager:

@Service
public class HibernateService {

    @PersistenceContext
    private EntityManager entityManager;

    public <R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass) {
        return getSession().createNativeQuery(sqlString, resultClass);
    }

    public NativeQuery createNativeQuery(String sqlString) {
        return getSession().createNativeQuery(sqlString);
    }

    public Session getSession() {
        return entityManager.unwrap(Session.class);
    }
}

you can add more methods to reduce amount of written code.

Using Hibernate 5 simple check the below

-- Check the base package is scan (HibernateConfig.java)

-- Check the valid annotation in file @Configuration @EnableTransactionManagement

-- check the all valid beans are created or not LocalSessionFactoryBean,HibernateTransactionManager,HibernateTemplate

Related