我尝试使用PersistenceContext
注释来注入实体管理器,但是我得到以下异常。
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'Foo' available
然后我做了一些研究,在每个例子中,配置类中的bean都有我在persistence.xml中的相同信息。
我们是否应该只使用持久性单元名称注入实体管理器?
这是我的代码
@Component
public class UnitOfWork {
@PersistenceContext(unitName="Foo")
private EntityManager entityManager;
}
@Configuration
@ComponentScan("com.foo.package")
public class Config {
}
META-INF文件夹中的Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="Foo">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/foo?useSSL=false" />
<property name="hibernate.connection.username" value="foo"/>
<property name="hibernate.connection.password" value="foo" />
</properties>
</persistence-unit>
</persistence>
Pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org-springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org-springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
答案 0 :(得分:1)
您仍需要定义LocalContainerEntityManagerFactory
以在应用程序上下文中使用EntityManagerFactory
。
如果没有一个不起作用,LocalContainerEntityManagerFactory
将使用persistence.xml
(如果存在)来配置自己。