使用 Java Spring 和 Hibernate 和 EntityManager 在 @Transactional 方法中提交事务的问题
Problem with transaction commit in @Transactional methods using Java Spring and Hibernate and EntityManager
我正在尝试学习 Spring,Hibernate 与 H2 数据库使用 maven 构建代码。目前我有一些问题如何正确使用 @Transactional 注释来自动启动事务并在例如时提交事务。 entityManager.persist 完成成功或回滚。
我的测试项目很简单。 POJO class 是个人,包含名字、姓氏和电子邮件地址。有一个服务 class PersonSerice,它是一个提供 CRUD 功能以添加、更改、读取和删除人员数据的接口。有调用 DAO class 方法的 PersonServiceImpl。这里是方法的示例代码 PersonDAOImpl::createPerson
使用
public void createPerson(Person person) {
entityManager.getTransaction().begin();
entityManager.persist(person);
entityManager.getTransaction().commit();
}
一切正常。有一个 Hibernate SQL 输出
"Hibernate:
call next value for hibernate_sequence Hibernate:
insert
into
person
(email, nachname, vorname, id)
values
(?, ?, ?, ?)"
我想摆脱手动调用 entityManager.getTransaction().commit();
所以我尝试在调用 DAO 方法的 ServiceImpl 方法中编写 @Transactional
public void createPerson(Person person) {
entityManager.getTransaction().begin();
entityManager.persist(person);
entityManager.getTransaction().commit();
}
现在不能正常工作。我刚明白。
" 休眠:
调用 hibernate_sequence 的下一个值
“
数据库中写入了一些内容,但我无法列出所有条目或在不手动提交的情况下删除它们。
所以我目前不知道出了什么问题,也不知道如何让@Transactional 自动执行提交。
Eclipse 调试器中显示的部分 entityManager 内容如下:
entityManager $Proxy26 (id=33)
h ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler (id=116)
containerManaged false
exceptionTranslator null
假的
synchronizedWithTransaction false
目标 SessionImpl (id=122)
actionQueue 动作队列 (id=306)
...
autoJoinTransactions 真
...
我想我的主要问题可能在 xml 资源文件中,所以我想在这里展示它们。
这是我的 Beans.xlm (./src/main/resources/Beans.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="maven.springhibernateh2.basic"></context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${db.driverClassName}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>database.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<!-- Definition des JpaTransactionManagers -->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Acitvation of @Transactional Annotation -->
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="roland.egger.maven.springhibernate" />
<property name="dataSource" ref="dataSource" />
</bean>
<context:spring-configured />
<context:annotation-config />
</beans>
一行可能有问题。 "<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />"
因为我的 pom.xml 中没有 aspectj 依赖项。但是添加它们并没有改变任何东西,我不知道需要什么才能让 @Transactional 按预期工作。
现在是其他文件。
这是我的 persistence.xml (./src/main/resources/META-INF/persistence.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="roland.egger.maven.springhibernate" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>maven.springhibernateh2.basic.Person</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
这是我的 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>roland.egger</groupId>
<artifactId>maven.springhibernateh2.basic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<slf4j.version>1.7.30</slf4j.version>
<spring.version>5.2.5.RELEASE</spring.version>
<hibernate.version>5.4.15.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Fuer den RollingFileAppender -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
这里database.properties
db.driverClassName=org.h2.Driver
db.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
db.username=sa
db.password=
这里Person.java
package maven.springhibernateh2.basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private int personId;
@Column(name = "vorname")
private String Vorname;
@Column(name = "nachname")
private String Nachname;
@Column(name = "email")
private String Emailadresse;
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public String getVorname() {
return Vorname;
}
public void setVorname(String vorname) {
Vorname = vorname;
}
public String getNachname() {
return Nachname;
}
public void setNachname(String nachname) {
Nachname = nachname;
}
public String getEmailadresse() {
return Emailadresse;
}
public void setEmailadresse(String emailadresse) {
Emailadresse = emailadresse;
}
public String toString() {
return "Person [PersonId=" + personId + ", Vorname=" + Vorname + ", Nachname=" + Nachname + ", Emailadresse=" + Emailadresse + "]";
}
}
PersonService.java
package maven.springhibernateh2.basic;
import java.util.List;
public interface PersonService {
public abstract void addPerson(Person person);
public abstract Person fetchPersonById(int personId);
public abstract void deletePersonByID(int personId);
public abstract void updatePersonEmailByID(String newEmail, int personId);
public abstract List<Person> getAllPersonInfo();
}
PersonServiceImpl.java
package maven.springhibernateh2.basic;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("personService")
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Transactional
public void addPerson(Person person) {
personDAO.createPerson(person);
}
@Transactional
public Person fetchPersonById(int personId) {
return personDAO.getPersonById(personId);
}
@Transactional
public void deletePersonByID(int personId) {
personDAO.deletePersonByID(personId);
}
@Transactional
public void updatePersonEmailByID(String newEmail, int personId) {
personDAO.updatePersonEmailByID(newEmail, personId);
}
@Transactional
public List<Person> getAllPersonInfo() {
return personDAO.getAllPersonData();
}
}
PersonDAO.java
package maven.springhibernateh2.basic;
import java.util.List;
public interface PersonDAO {
public abstract void createPerson(Person person);
public abstract Person getPersonById(int personId);
public abstract void deletePersonByID(int personId);
public abstract void updatePersonEmailByID(String newEmail, int personId);
public abstract List<Person> getAllPersonData();
}
PersonDAOImpl.java
package maven.springhibernateh2.basic;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
@Repository
public class PersonDAOImpl implements PersonDAO {
@PersistenceUnit(name = "roland.egger.maven.springhibernate")
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
@PersistenceUnit
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
this.entityManager = this.entityManagerFactory.createEntityManager();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void createPerson(Person person) {
entityManager.persist(person);
}
public Person getPersonById(int personId) {
Person person = entityManager.find(Person.class, personId);
return person;
}
public void deletePersonByID(int personId) {
Person person = getPersonById(personId);
if (person != null) {
//entityManager.getTransaction().begin();
entityManager.remove(person);
//entityManager.getTransaction().commit();
}
}
public void updatePersonEmailByID(String newEmail, int personId) {
Person person = getPersonById(personId);
if (person != null)
{
entityManager.getTransaction().begin();
person.setEmailadresse(newEmail);
entityManager.getTransaction().commit();
}
}
public List<Person> getAllPersonData() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> rootEntry = cq.from(Person.class);
CriteriaQuery<Person> all = cq.select(rootEntry);
TypedQuery<Person> allQuery = entityManager.createQuery(all);
return allQuery.getResultList();
}
}
对不起,我发布了源代码,但我希望它能帮助其他人理解我在做什么以及如何解决问题以使交易正常运行,而无需手动将它们写入代码。
当您使用@PersistenceUnit 时,您需要create/destroy EntityManager 并手动管理事务。如果你想使用 spring @Transactional,你需要删除由 @PersistenceUnit 注释的 entityManagerFactory,而是在你的 entityManager 变量上使用 @PersistenceContext,如下所示。
@PersistenceContext
private EntityManager entityManager;
原因是,当您使用 @PersistenceContext 时,您定义了一个容器管理的 bean(这里是 spring 管理的),这样您就不需要显式地 commit/rollback 您的事务,在另一方面,使用@PersistenceUnit 指定要处理事务。
更新:
与提到"No EntityManager with actual transaction available for current thread"的最新错误相关:
- 如果不这样做,您可以从配置中删除模式="aspectj"
需要使用 aspectj 并且可以依赖 spring 默认 AOP。后
从 Beans.xml 中删除 mode="aspectj" 你的代码应该可以工作
立即。
- 或者调整您的配置以正确实现 aspectj。至少你
需要将 aspectj 依赖项添加到您的项目 pom 并将 "context:load-time-weaver" 定义添加到 Beans.xml。请检查 spring 事务管理文档以了解 aspectj 的用法。
希望对您有所帮助。
我试图回答 Ali Gelenkers 的建议,但评论太短了,我明白了,之后我又遇到了 entityManager 的另一个问题。
感谢 Ali Gelenker,我被告知我的 EntityManagerFactory 的 PersonDAOImpl class 中的 @PersistenceUnit 及其 setter 函数会导致问题,应该使用 @PersistenceContext。
这是我的 PersonDaoImpl
新代码的一部分
@Repository
public class PersonDAOImpl implements PersonDAO {
private EntityManagerFactory entityManagerFactory;
@PersistenceContext
private EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
this.entityManager = this.entityManagerFactory.createEntityManager();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void createPerson(Person person) {
entityManager.persist(person);
}
...
现在 setter setEntityManagerFactory 和 setter setEntityManager 都没有被调用。问题出现在调用 entityManager.persist(person) 期间的 createPerson 方法中。
entityManager 调用抛出以下异常:
" javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call "
在此异常之前,entityManager 在 Eclipse 的调试器中显示以下内容。:
entityManager $Proxy26 (id=40)
h SharedEntityManagerCreator$SharedEntityManagerInvocationHandler (id=47)
logger LogAdapter$Slf4jLocationAwareLog (id=51)
properties null
proxyClassLoader Launcher$AppClassLoader (id=55)
synchronizedWithTransaction true
targetFactory $Proxy23 (id=62)
完整的控制台输出为:
INFO | 2020-05-09 22:44:44,953 | | | main | maven.springhibernateh2.basic.CRUDTest - Programmanfang...
INFO | 2020-05-09 22:44:45,486 | | | main | org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [name: roland.egger.maven.springhibernate]
INFO | 2020-05-09 22:44:45,532 | | | main | org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.15.Final
INFO | 2020-05-09 22:44:45,657 | | | main | org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
INFO | 2020-05-09 22:44:46,193 | | | main | org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:
drop table if exists person CASCADE
Hibernate:
drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:
create table person (
id integer not null,
email varchar(255),
nachname varchar(255),
vorname varchar(255),
primary key (id)
)
INFO | 2020-05-09 22:44:46,877 | | | main | org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
INFO | 2020-05-09 22:44:46,884 | | | main | org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'roland.egger.maven.springhibernate'
ERROR | 2020-05-09 22:44:46,987 | | | main | maven.springhibernateh2.basic.CRUDTest - javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
INFO | 2020-05-09 22:44:46,987 | | | main | maven.springhibernateh2.basic.CRUDTest - Programmende...
INFO | 2020-05-09 22:44:46,988 | | | main | org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'roland.egger.maven.springhibernate'
需要什么才能使 entityManager 可用于当前线程?
更新:
感谢 Ali Gelenkers 的更新建议,我让它工作了:)
对于我的测试项目,我选择了没有 aspectj 的最简单的解决方案。
这是我 Beans.xml 的更改部分:
...
<!-- <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" /> -->
<tx:annotation-driven transaction-manager="transactionManager" />
...
<aop:config proxy-target-class="true"/>
现在一切正常,无需手动交易调用。
非常感谢:)
更新 2
上面的代码正在运行,我可以在 Eclipse 中使用 mvn exec (mvn exec:java -Dexec.mainClass="maven.springhibernateh2.basic.CRUDTest") 运行。不幸的是,我无法为 运行 构建可执行 jar。请参见:
problem creating an executable jar with maven using spring 5 and hibernate 5 => BeanDefinitionParsingException
我猜 pom.xml 有问题。我很乐意提出任何建议。
我正在尝试学习 Spring,Hibernate 与 H2 数据库使用 maven 构建代码。目前我有一些问题如何正确使用 @Transactional 注释来自动启动事务并在例如时提交事务。 entityManager.persist 完成成功或回滚。
我的测试项目很简单。 POJO class 是个人,包含名字、姓氏和电子邮件地址。有一个服务 class PersonSerice,它是一个提供 CRUD 功能以添加、更改、读取和删除人员数据的接口。有调用 DAO class 方法的 PersonServiceImpl。这里是方法的示例代码 PersonDAOImpl::createPerson 使用
public void createPerson(Person person) {
entityManager.getTransaction().begin();
entityManager.persist(person);
entityManager.getTransaction().commit();
}
一切正常。有一个 Hibernate SQL 输出
"Hibernate: call next value for hibernate_sequence Hibernate: insert into person (email, nachname, vorname, id) values (?, ?, ?, ?)"
我想摆脱手动调用 entityManager.getTransaction().commit(); 所以我尝试在调用 DAO 方法的 ServiceImpl 方法中编写 @Transactional
public void createPerson(Person person) {
entityManager.getTransaction().begin();
entityManager.persist(person);
entityManager.getTransaction().commit();
}
现在不能正常工作。我刚明白。 " 休眠: 调用 hibernate_sequence 的下一个值 “ 数据库中写入了一些内容,但我无法列出所有条目或在不手动提交的情况下删除它们。 所以我目前不知道出了什么问题,也不知道如何让@Transactional 自动执行提交。 Eclipse 调试器中显示的部分 entityManager 内容如下:
entityManager $Proxy26 (id=33)
h ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler (id=116)
containerManaged false
exceptionTranslator null
假的
synchronizedWithTransaction false
目标 SessionImpl (id=122)
actionQueue 动作队列 (id=306)
...
autoJoinTransactions 真
...
我想我的主要问题可能在 xml 资源文件中,所以我想在这里展示它们。 这是我的 Beans.xlm (./src/main/resources/Beans.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="maven.springhibernateh2.basic"></context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${db.driverClassName}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>database.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<!-- Definition des JpaTransactionManagers -->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Acitvation of @Transactional Annotation -->
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="roland.egger.maven.springhibernate" />
<property name="dataSource" ref="dataSource" />
</bean>
<context:spring-configured />
<context:annotation-config />
</beans>
一行可能有问题。 "<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />"
因为我的 pom.xml 中没有 aspectj 依赖项。但是添加它们并没有改变任何东西,我不知道需要什么才能让 @Transactional 按预期工作。
现在是其他文件。
这是我的 persistence.xml (./src/main/resources/META-INF/persistence.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="roland.egger.maven.springhibernate" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>maven.springhibernateh2.basic.Person</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
这是我的 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>roland.egger</groupId>
<artifactId>maven.springhibernateh2.basic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<slf4j.version>1.7.30</slf4j.version>
<spring.version>5.2.5.RELEASE</spring.version>
<hibernate.version>5.4.15.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Fuer den RollingFileAppender -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
这里database.properties
db.driverClassName=org.h2.Driver
db.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
db.username=sa
db.password=
这里Person.java
package maven.springhibernateh2.basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private int personId;
@Column(name = "vorname")
private String Vorname;
@Column(name = "nachname")
private String Nachname;
@Column(name = "email")
private String Emailadresse;
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public String getVorname() {
return Vorname;
}
public void setVorname(String vorname) {
Vorname = vorname;
}
public String getNachname() {
return Nachname;
}
public void setNachname(String nachname) {
Nachname = nachname;
}
public String getEmailadresse() {
return Emailadresse;
}
public void setEmailadresse(String emailadresse) {
Emailadresse = emailadresse;
}
public String toString() {
return "Person [PersonId=" + personId + ", Vorname=" + Vorname + ", Nachname=" + Nachname + ", Emailadresse=" + Emailadresse + "]";
}
}
PersonService.java
package maven.springhibernateh2.basic;
import java.util.List;
public interface PersonService {
public abstract void addPerson(Person person);
public abstract Person fetchPersonById(int personId);
public abstract void deletePersonByID(int personId);
public abstract void updatePersonEmailByID(String newEmail, int personId);
public abstract List<Person> getAllPersonInfo();
}
PersonServiceImpl.java
package maven.springhibernateh2.basic;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("personService")
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
@Transactional
public void addPerson(Person person) {
personDAO.createPerson(person);
}
@Transactional
public Person fetchPersonById(int personId) {
return personDAO.getPersonById(personId);
}
@Transactional
public void deletePersonByID(int personId) {
personDAO.deletePersonByID(personId);
}
@Transactional
public void updatePersonEmailByID(String newEmail, int personId) {
personDAO.updatePersonEmailByID(newEmail, personId);
}
@Transactional
public List<Person> getAllPersonInfo() {
return personDAO.getAllPersonData();
}
}
PersonDAO.java
package maven.springhibernateh2.basic;
import java.util.List;
public interface PersonDAO {
public abstract void createPerson(Person person);
public abstract Person getPersonById(int personId);
public abstract void deletePersonByID(int personId);
public abstract void updatePersonEmailByID(String newEmail, int personId);
public abstract List<Person> getAllPersonData();
}
PersonDAOImpl.java
package maven.springhibernateh2.basic;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
@Repository
public class PersonDAOImpl implements PersonDAO {
@PersistenceUnit(name = "roland.egger.maven.springhibernate")
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
@PersistenceUnit
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
this.entityManager = this.entityManagerFactory.createEntityManager();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void createPerson(Person person) {
entityManager.persist(person);
}
public Person getPersonById(int personId) {
Person person = entityManager.find(Person.class, personId);
return person;
}
public void deletePersonByID(int personId) {
Person person = getPersonById(personId);
if (person != null) {
//entityManager.getTransaction().begin();
entityManager.remove(person);
//entityManager.getTransaction().commit();
}
}
public void updatePersonEmailByID(String newEmail, int personId) {
Person person = getPersonById(personId);
if (person != null)
{
entityManager.getTransaction().begin();
person.setEmailadresse(newEmail);
entityManager.getTransaction().commit();
}
}
public List<Person> getAllPersonData() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> rootEntry = cq.from(Person.class);
CriteriaQuery<Person> all = cq.select(rootEntry);
TypedQuery<Person> allQuery = entityManager.createQuery(all);
return allQuery.getResultList();
}
}
对不起,我发布了源代码,但我希望它能帮助其他人理解我在做什么以及如何解决问题以使交易正常运行,而无需手动将它们写入代码。
当您使用@PersistenceUnit 时,您需要create/destroy EntityManager 并手动管理事务。如果你想使用 spring @Transactional,你需要删除由 @PersistenceUnit 注释的 entityManagerFactory,而是在你的 entityManager 变量上使用 @PersistenceContext,如下所示。
@PersistenceContext
private EntityManager entityManager;
原因是,当您使用 @PersistenceContext 时,您定义了一个容器管理的 bean(这里是 spring 管理的),这样您就不需要显式地 commit/rollback 您的事务,在另一方面,使用@PersistenceUnit 指定要处理事务。
更新:
与提到"No EntityManager with actual transaction available for current thread"的最新错误相关:
- 如果不这样做,您可以从配置中删除模式="aspectj" 需要使用 aspectj 并且可以依赖 spring 默认 AOP。后 从 Beans.xml 中删除 mode="aspectj" 你的代码应该可以工作 立即。
- 或者调整您的配置以正确实现 aspectj。至少你 需要将 aspectj 依赖项添加到您的项目 pom 并将 "context:load-time-weaver" 定义添加到 Beans.xml。请检查 spring 事务管理文档以了解 aspectj 的用法。
希望对您有所帮助。
我试图回答 Ali Gelenkers 的建议,但评论太短了,我明白了,之后我又遇到了 entityManager 的另一个问题。 感谢 Ali Gelenker,我被告知我的 EntityManagerFactory 的 PersonDAOImpl class 中的 @PersistenceUnit 及其 setter 函数会导致问题,应该使用 @PersistenceContext。 这是我的 PersonDaoImpl
新代码的一部分@Repository
public class PersonDAOImpl implements PersonDAO {
private EntityManagerFactory entityManagerFactory;
@PersistenceContext
private EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
this.entityManager = this.entityManagerFactory.createEntityManager();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void createPerson(Person person) {
entityManager.persist(person);
}
...
现在 setter setEntityManagerFactory 和 setter setEntityManager 都没有被调用。问题出现在调用 entityManager.persist(person) 期间的 createPerson 方法中。 entityManager 调用抛出以下异常:
" javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call "
在此异常之前,entityManager 在 Eclipse 的调试器中显示以下内容。:
entityManager $Proxy26 (id=40)
h SharedEntityManagerCreator$SharedEntityManagerInvocationHandler (id=47)
logger LogAdapter$Slf4jLocationAwareLog (id=51)
properties null
proxyClassLoader Launcher$AppClassLoader (id=55)
synchronizedWithTransaction true
targetFactory $Proxy23 (id=62)
完整的控制台输出为:
INFO | 2020-05-09 22:44:44,953 | | | main | maven.springhibernateh2.basic.CRUDTest - Programmanfang...
INFO | 2020-05-09 22:44:45,486 | | | main | org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [name: roland.egger.maven.springhibernate]
INFO | 2020-05-09 22:44:45,532 | | | main | org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.15.Final
INFO | 2020-05-09 22:44:45,657 | | | main | org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
INFO | 2020-05-09 22:44:46,193 | | | main | org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:
drop table if exists person CASCADE
Hibernate:
drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:
create table person (
id integer not null,
email varchar(255),
nachname varchar(255),
vorname varchar(255),
primary key (id)
)
INFO | 2020-05-09 22:44:46,877 | | | main | org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
INFO | 2020-05-09 22:44:46,884 | | | main | org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'roland.egger.maven.springhibernate'
ERROR | 2020-05-09 22:44:46,987 | | | main | maven.springhibernateh2.basic.CRUDTest - javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
INFO | 2020-05-09 22:44:46,987 | | | main | maven.springhibernateh2.basic.CRUDTest - Programmende...
INFO | 2020-05-09 22:44:46,988 | | | main | org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'roland.egger.maven.springhibernate'
需要什么才能使 entityManager 可用于当前线程?
更新: 感谢 Ali Gelenkers 的更新建议,我让它工作了:) 对于我的测试项目,我选择了没有 aspectj 的最简单的解决方案。 这是我 Beans.xml 的更改部分: ...
<!-- <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" /> -->
<tx:annotation-driven transaction-manager="transactionManager" />
...
<aop:config proxy-target-class="true"/>
现在一切正常,无需手动交易调用。 非常感谢:)
更新 2 上面的代码正在运行,我可以在 Eclipse 中使用 mvn exec (mvn exec:java -Dexec.mainClass="maven.springhibernateh2.basic.CRUDTest") 运行。不幸的是,我无法为 运行 构建可执行 jar。请参见: problem creating an executable jar with maven using spring 5 and hibernate 5 => BeanDefinitionParsingException 我猜 pom.xml 有问题。我很乐意提出任何建议。