Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration

Do Nhu Vy picture Do Nhu Vy · Feb 20, 2018 · Viewed 18.9k times · Source

I am using Spring Boot 2.0.0.RC1 (It include Spring Framework 5.0.3.RELEASE), Hibernate 5.2.12.Final, JPA 2.1 API 1.0.0.Final .

I have a class

package com.example;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManagerFactory;

@Configuration
public class BeanConfig {

    @Autowired
    EntityManagerFactory emf;

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

}

Then error

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

Description:

Parameter 0 of method sessionFactory in com.example.BeanConfig required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.


Action:

Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration.


Process finished with exit code 1

How to fix this?

Answer

ootero picture ootero · Feb 21, 2018

If you include this:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

You won't have to autowire the Entity Manager or provide a Session Factory bean.

You would only need to provide JpaRepository interfaces like:

public interface ActorDao extends JpaRepository<Actor, Integer> {
}

where Actor is a JPA entity class and Integer is the ID / primary key and inject ActorDao in a service impl class.