【发布时间】:2015-08-15 01:58:20
【问题描述】:
我可能遗漏了关于如何使用 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
【问题讨论】:
标签: java jpa spring-boot entitymanager