java - JPA+Spring引导: TransactionRequiredException on CRUD operations

标签 java jpa spring-boot entitymanager

我可能遗漏了一些关于如何使用 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/

相关文章:

java - 如何使用Hibernate获取SQL Server存储过程的执行结果?

java - openfaces 树表缺少 js

java - 生成随机矩形

java - JPA 2.1 自定义命名策略?

java - Spring寻找我没有使用java.sql.SQLSyntaxErrorException : Table 'meetings.meeting' doesn't exist创建的表

java - 如何在 Java 中对字符串数组中的日期进行排序?

java - 需要帮助将标准 SQL 查询转换为 JPA Criteria 查询

spring-boot - 实体类名转换为带下划线的SQL表名

spring-boot - 使用 H2 DB 将 Spring Boot 部署到 Heroku

java - ElasticSearch 从多个位置获取具有一个值的数据