[英]JPA + Spring Boot: TransactionRequiredException on CRUD operations
我可能会缺少一些有关如何使用JPA的基础知识,但是我遇到了javax.persistence.TransactionRequiredException: No transactional EntityManager available
当我尝试从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类的类具有要加入的事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.