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
これを修正する方法は?
これを含める場合:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Entity Manager
を自動配線したり、Session Factory
Beanを提供したりする必要はありません。
次のようなJpaRepositoryインターフェイスを提供するだけで済みます。
public interface ActorDao extends JpaRepository<Actor, Integer> {
}
ここで、Actor
はJPA
エンティティクラスであり、Integer
はID /主キーであり、ActorDao
implクラスにservice
を挿入します。
発生している特定のエラーは、@Qualifier
アノテーションが原因で発生します。 Springは、タイプEntityManagerFactory
のBeanを探す代わりに、あなたが言及した特定の名前のBeanを探しています。注釈を削除するだけです。
ただし、これを修正すると、SessionFactoryを構築するメソッドにもBeanを挿入するため、SpringBootは循環依存に関連する別のエラーを生成します。これを回避するには、ConfigクラスにsessionFactory
を既に挿入しているため、EntityManagerFactory
メソッドからパラメーターを完全に削除します。
このコードは機能します:
@Bean
public SessionFactory sessionFactory() {
return emf.unwrap(SessionFactory.class);
}
BeanConfig
では、@PersistenceUnit
ではなく@Autowired
を介してJPAEntityManager
を挿入する必要があります。
また、Hibernate SessionFactoryはすでに内部で作成されており、いつでもgetSessionFactory
をアンラップできるため、EntityManagerFactory
を削除します。
このような:
@Configuration
public class BeanConfig {
@PersistenceUnit
EntityManagerFactory emf;
}