web-dev-qa-db-ja.com

構成でタイプ 'javax.persistence.EntityManagerFactory'のBeanを定義することを検討してください

Spring Boot 2.0.0.RC1(Spring Framework 5.0.3.RELEASEを含む)、Hibernate 5.2.12.Final、JPA 2.1 API1.0.0.Finalを使用しています。

クラスがあります

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);
    }

}

次にエラー

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

これを修正する方法は?

3
Do Nhu Vy

これを含める場合:

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

Entity Managerを自動配線したり、Session FactoryBeanを提供したりする必要はありません。

次のようなJpaRepositoryインターフェイスを提供するだけで済みます。

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

ここで、ActorJPAエンティティクラスであり、IntegerはID /主キーであり、ActorDaoimplクラスにserviceを挿入します。

6
ootero

発生している特定のエラーは、@Qualifierアノテーションが原因で発生します。 Springは、タイプEntityManagerFactoryのBeanを探す代わりに、あなたが言及した特定の名前のBeanを探しています。注釈を削除するだけです。

ただし、これを修正すると、SessionFactoryを構築するメソッドにもBeanを挿入するため、SpringBootは循環依存に関連する別のエラーを生成します。これを回避するには、ConfigクラスにsessionFactoryを既に挿入しているため、EntityManagerFactoryメソッドからパラメーターを完全に削除します。

このコードは機能します:

@Bean
public SessionFactory sessionFactory() {
        return emf.unwrap(SessionFactory.class);
}
0
HL'REB

BeanConfigでは、@PersistenceUnitではなく@Autowiredを介してJPAEntityManagerを挿入する必要があります。

また、Hibernate SessionFactoryはすでに内部で作成されており、いつでもgetSessionFactoryをアンラップできるため、EntityManagerFactoryを削除します。

このような:

@Configuration
public class BeanConfig {

    @PersistenceUnit
    EntityManagerFactory emf;

}
0
Vlad Mihalcea