TransactionRequiredException: No EntityManager with actual transaction available 怎么来的?persist、remove、merge 与 @Modifying 各报什么?readOnly 里 persist 为什么有时不落库?这篇在 Spring Boot 4.0.8 上逐个触发。
没有事务,em.persist → 异常 TransactionRequiredException:No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call;之后 person 表 0 行,item 表 0 行 对照:@Transactional 方法里 em.persist → 没有异常;之后 person 表 1 行,item 表 0 行
没有事务抛异常,有事务正常。
没有事务,em.find 读到:Person 对象 没有事务,em.remove → 异常 TransactionRequiredException:No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call 没有事务,em.merge → 异常 TransactionRequiredException:No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call;之后 person 表 0 行,item 表 0 行
读不需要事务,写需要。
Spring Data 的 save(自带 @Transactional) → 没有异常;之后 person 表 1 行,item 表 0 行 @Modifying @Query 没有事务 → 异常 InvalidDataAccessApiUsageException:No active transaction for update or delete query 同一条查询,方法上加 @Transactional → 影响 2 行 em.createQuery(update …).executeUpdate() 没有事务 → 异常 TransactionRequiredException:No active transaction for update or delete query;之后 person 表 0 行,item 表 0 行
Spring Data 转换了异常类型。
@Transactional(readOnly = true) 里 em.persist(Person,主键 IDENTITY) → 没有异常;之后 person 表 1 行,item 表 0 行 @Transactional(readOnly = true) 里 em.persist(Item,主键 SEQUENCE) → 没有异常;之后 person 表 0 行,item 表 0 行 对照:普通 @Transactional 里 em.persist(Item,主键 SEQUENCE) → 没有异常;之后 person 表 0 行,item 表 1 行
IDENTITY 落库,SEQUENCE 不落库也不报错。
外层方法没有事务,同类里调用 @Transactional 方法(自调用) → 异常 TransactionRequiredException:No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call;之后 person 表 0 行,item 表 0 行
不经过代理就没有事务。
@Transactional 方法里新开线程 em.persist → 异常 RuntimeException ← TransactionRequiredException:No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call;之后 person 表 0 行,item 表 0 行
事务绑在线程上。