简体   繁体   English

使用 Java Spring 和 Hibernate 和 EntityManager 的 @Transactional 方法中的事务提交问题

[英]Problem with transaction commit in @Transactional methods using Java Spring and Hibernate and EntityManager

I'm trying to learn Spring, Hibernate with the H2 database usinge maven to build the code.我正在尝试使用 H2 数据库学习 Spring、Hibernate 来构建代码。 Currently I have some problems how to use the @Transactional annotation correctly to automatic start the transaction and commit the transaction when eg entityManager.persist is done successful or rollback.目前我有一些问题如何正确使用@Transactional 注释来自动启动事务并在例如entityManager.persist 成功或回滚时提交事务。

My test project is very simple.我的测试项目非常简单。 The POJO class is Person and contains first name, family name and email address. POJO class 是人,包含名字、姓氏和 email 地址。 There is a Service class PersonSerice that is an interface that offers CRUD functions to add, change, read and delete person data.有一个 Service class PersonSerice 是一个提供 CRUD 功能以添加、更改、读取和删除人员数据的接口。 There is the PersonServiceImpl that calls the methods of the DAO class.有调用DAO class 方法的PersonServiceImpl。 And here the sample Code of the method PersonDAOImpl::createPerson Using这里是 PersonDAOImpl::createPerson 方法的示例代码

public void createPerson(Person person) {
    entityManager.getTransaction().begin();
    entityManager.persist(person);
    entityManager.getTransaction().commit();
}

Everything works as expected.一切都按预期工作。 There is a Hibernate SQL output有一个 Hibernate SQL output

"Hibernate: call next value for hibernate_sequence Hibernate: insert into person (email, nachname, vorname, id) values (?, ?, ?, ?)" “休眠:调用 hibernate_sequence Hibernate 的下一个值:插入人(电子邮件,nachname,vorname,id)值(?,?,?,?)”

I want to get rid of manually calling entityManager.getTransaction().commit();我想摆脱手动调用entityManager.getTransaction().commit(); So I tried to write @Transactional at the ServiceImpl method that call the DAO method所以我尝试在调用DAO方法的ServiceImpl方法上写@Transactional

    public void createPerson(Person person) {
    entityManager.getTransaction().begin();
    entityManager.persist(person);
    entityManager.getTransaction().commit();
}

Now it does not work properly.现在它不能正常工作。 I just get.我才明白。 " Hibernate: call next value for hibernate_sequence " There is something written into the database but I cannot list all entries or remove them without a manually commit. " Hibernate: call next value for hibernate_sequence " 数据库中写入了一些内容,但如果没有手动提交,我无法列出所有条目或删除它们。 So I currently don't know what is wrong and how I can get @Transactional do the commit automatically.所以我目前不知道出了什么问题以及如何让@Transactional 自动提交。 Here part of the entityManager content shown in Eclipse debugger:这里部分 entityManager 内容显示在 Eclipse 调试器中:

entityManager $Proxy26 (id=33) h ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler (id=116) entityManager $Proxy26 (id=33) h ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler (id=116)
containerManaged false容器管理假
exceptionTranslator null jta false synchronizedWithTransaction false exceptionTranslator null jta false synchronizedWithTransaction false
target SessionImpl (id=122)目标 SessionImpl (id=122)
actionQueue ActionQueue (id=306)动作队列动作队列(id=306)
... autoJoinTransactions true ... autoJoinTransactions 真
... ...

I guess my main problems could be in the xml resource files so I want to show them here.我想我的主要问题可能在 xml 资源文件中,所以我想在这里展示它们。 Here is my Beans.xlm (./src/main/resources/Beans.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>

One line is maybe a problem.一条线可能是个问题。 "<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />" As I don't have aspectj dependencies in my pom. "<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />"因为我的 pom.xml 中没有 aspectj 依赖项。 But adding them didn't change anything and I don't know what is needed to get @Transactional working as expected.但是添加它们并没有改变任何东西,我不知道要让@Transactional 按预期工作需要什么。

Now the other files.现在是其他文件。

Here is my persistence.xml (./src/main/resources/META-INF/persistence.xml)这是我的持久性。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>

Here my pom.xml这是我的 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>

Here database.properties这里database.properties

db.driverClassName=org.h2.Driver
db.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
db.username=sa
db.password=

Here Person.java这里人.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 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 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 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 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();
    }

}

Excuse me for posting the source code but I hope that it helps others to understand what I am doing and how the problem can be solved to get the transaction working without manually writing them into the code.请原谅我发布源代码,但我希望它可以帮助其他人了解我在做什么以及如何解决问题以使事务正常工作,而无需手动将它们写入代码。

When you use @PersistenceUnit you need to create/destroy EntityManager and manually manage transactions.当您使用 @PersistenceUnit 时,您需要创建/销毁 EntityManager 并手动管理事务。 If you want to use spring @Transactional you need to remove entityManagerFactory which is annotated by @PersistenceUnit, and instead use @PersistenceContext on your entityManager variable as below.如果要使用 spring @Transactional,则需要删除由 @PersistenceUnit 注释的 entityManagerFactory,而是在 entityManager 变量上使用 @PersistenceContext,如下所示。

@PersistenceContext
private EntityManager entityManager;

The reason is, when you use @PersistenceContext you define a container managed bean(here it is spring managed) so that you don't need to explicitly commit/rollback your transactions, on the other hand with @PersistenceUnit you specify that you want to handle the transactions.原因是,当您使用 @PersistenceContext 时,您定义了一个容器托管 bean(这里是 spring 托管),因此您不需要显式提交/回滚您的事务,另一方面使用 @PersistenceUnit 您指定您想要处理交易。

Update:更新:

Related with the latest error which mentions about "No EntityManager with actual transaction available for current thread":与提到“当前线程没有可用的实际事务的实体管理器”的最新错误相关:

  • You can either remove mode="aspectj" from configuration if you don't need to use aspectj and can rely on spring default AOP.如果您不需要使用 aspectj,您可以从配置中删除 mode="aspectj" 并且可以依赖 spring 默认 AOP。 After removing mode="aspectj" from Beans.xml your code should work immediately.从 Beans.xml 中删除 mode="aspectj" 后,您的代码应该可以立即运行。
  • Or adjust your config to correctly implement aspectj.或者调整您的配置以正确实现 aspectj。 At least you need to add aspectj dependencies to your project pom and add "context:load-time-weaver" definition to Beans.xml.至少您需要将 aspectj 依赖项添加到您的项目 pom 并将“context:load-time-weaver”定义添加到 Beans.xml。 Please check spring transaction management docs for aspectj usage.请查看 spring 事务管理文档以了解 aspectj 的使用。

Hope this helps.希望这可以帮助。

I tried to answer on Ali Gelenkers suggestion but the comments are to short and I see, that I get into another problem with the entityManager afterwards.我试图回答 Ali Gelenkers 的建议,但评论很短,我看到,之后我遇到了 entityManager 的另一个问题。 Thank to Ali Gelenker I was informed that @PersistenceUnit in my PersonDAOImpl class for my EntityManagerFactory and its setter function causes problems and that @PersistenceContext should be used.感谢 Ali Gelenker,我被告知我的 PersonDAOImpl class 中的 @PersistenceUnit 及其设置器 function 会导致问题,应该使用 @PersistenceContext。 Here the part of my new code of PersonDaoImpl这是我的 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);
    }
...

Now neither the setter setEntityManagerFactory nor the setter setEntityManager is called.现在既不调用 setter setEntityManagerFactory 也不调用 setter setEntityManager。 The problem occurs in the createPerson method during calling entityManager.persist(person).调用 entityManager.persist(person) 期间的 createPerson 方法出现问题。 The entityManager call throws the following exception: entityManager 调用会引发以下异常:

" javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call "

Before this exception the entityManager shows the follwing content in the debugger of Eclipse.:在此异常之前 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)

The complete console output is:完整的控制台 output 是:

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' 

What is needed to make the entityManager available for the current thread?需要什么才能使 entityManager 可用于当前线程?

Update: Thanks to the updated advice of Ali Gelenkers I got it working:) For my test project I've chosen the easiest solution without aspectj.更新:感谢 Ali Gelenkers 的更新建议,我得到了它的工作:) 对于我的测试项目,我选择了没有 aspectj 的最简单的解决方案。 Here the changed part of my Beans.xml: ...这是我的 Beans.xml 的更改部分:...

       <!--  <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />  -->
       <tx:annotation-driven transaction-manager="transactionManager" /> 
...
       <aop:config proxy-target-class="true"/>

Now everything works fine without manual transaction calls.现在一切正常,无需手动事务调用。 Thank you very much:)非常感谢:)

Update 2 The code above is working and I'm able to run it in Eclipse and with mvn exec (mvn exec:java -Dexec.mainClass="maven.springhibernateh2.basic.CRUDTest").更新 2上面的代码正在运行,我可以在 Eclipse 和 mvn exec (mvn exec:java -Dexec.mainClass="maven.springhibernateh2.basic.CRUDTest") 中运行它。 Unfortunately I am not able to build an executable jar to run it.不幸的是,我无法构建一个可执行的 jar 来运行它。 Please see: problem creating an executable jar with maven using spring 5 and hibernate 5 => BeanDefinitionParsingException I guess that the pom.xml has a problem. Please see: problem creating an executable jar with maven using spring 5 and hibernate 5 => BeanDefinitionParsingException I guess that the pom.xml has a problem. I would be very happy for any suggestions.我会很高兴有任何建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring-Hibernate @Transactional服务方法不会自动提交 - Spring-Hibernate @Transactional service methods do not automatically commit Spring 启动 + Hibernate + JPA 没有事务实体管理器可用 - Spring boot + Hibernate + JPA No transactional EntityManager available 在Spring中使用JPA EntityManager和Hibernate会话与共享事务管理器 - Using both JPA EntityManager and Hibernate session with shared transaction manager in Spring 方法完成时,Spring EntityManager提交事务 - Spring EntityManager Commit Transaction as method completes 在单个事务中运行spring @Transactional注释方法 - Run spring @Transactional annotated methods in a single transaction Hibernate Spring JPA javax.persistence.TransactionRequiredException:没有可用的事务性EntityManager - Hibernate Spring JPA javax.persistence.TransactionRequiredException: No transactional EntityManager available Spring / Hibernate @Transactional 不刷新事务,如果后跟第二个 @Transactional 调用 - Spring / Hibernate @Transactional not flushing transaction if followed by a second @Transactional call Spring和Hibernate:非事务性服务方法 - Spring & Hibernate: non transactional service methods Spring 数据 JPA + Hibernate 标记方法为事务 - Spring Data JPA + Hibernate Marking methods as Transactional 将Hibernate + Spring与3个事务数据库一起使用 - Using Hibernate + Spring with 3 Transactional Databases
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM