我可能遗漏了一些关于如何使用 JPA 的非常基本的东西,但是当我尝试从 DAO 执行 CRUD 操作(特别是操作)时,我收到 javax.persistence.TransactionRequiredException: No transactional EntityManager available
改变数据库。我正在使用 Spring Boot。
这是一个玩具示例,它提供了我的代码设置,因为您会注意到从 EntityManager 调用的所有方法仅轮询信息工作,但是一旦我尝试以某种方式更改数据库,我就会遇到问题:
@Repository
public class PersonJpa{
@PersistenceContext
private EntityManager em;
public void foo() {
Long id = 500l;
Person p = new Person(id, "lastName", "firstName");
// all of these calls work:
em.find(Person.class, id);
em.contains(p);
em.getReference(Person.class, id);
// this call causes exception:
em.remove(p);
}
}
这是我的 Spring Boot 配置:
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = {Info.BASE_PACKAGE})
@EntityScan(basePackages = {Info.BASE_PACKAGE})
public class PersonServiceConfiguration {
public static void main(String[] args) {
SpringApplication.run(PersonServiceConfiguration.class, args);
}
}
这是我的 application.yml
文件:
spring:
profiles.active: default
---
spring:
profiles: default
spring.datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db?autoReconnect=true
username: user
password: pwd
spring.jpa.show-sql: false
spring.jpa.database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
最佳答案
将@Transactional
添加到执行CRUD的类中,并确保调用CRUD类的类有一个要加入的事务。
关于java - JPA+Spring引导: TransactionRequiredException on CRUD operations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576371/