First, I make a quote of the Spring-Data JPA Documentation to justify why the delete method works in your case (I mean the option 2). 默认情况下,存储库实例上的 CRUD方法是事务性的.为了 读取操作已设置事务配置readOnly标志 确实,所有其他配置有普通的@Transactional 默认交易配置适用.有关详细信息,请参见 CrudRepository CRUD methods on repository instances are transactional by default. For reading operations the transaction configuration readOnly flag is set to true, all others are configured with a plain @Transactional so that default transaction configuration applies. For details see JavaDoc of CrudRepository delete方法实际上是CrudRepository的方法.您的存储库扩展了JpaRepository,该存储库扩展了CrudRespository,因此它属于CrudRepository接口,并且根据上面的引用是事务性的.The delete method is actually a method of the CrudRepository. Your repository extends JpaRepository which extends CrudRespository, so it belongs to CrudRepository interface and according the quote above is transactional.如果您阅读了事务查询方法,您将看到与选项 4 相同的知识,并且您将知道如何对存储库的所有方法应用自定义事务行为.另外,文档的示例61 显示的场景与选项 3 相同.If you read the section Transactional Query Method you will see that is the same that the option 4 and you will know how to apply a custom transactional behavior for all methods of your repository.Also, the Example 61 of the documentation shows the same scenario that the option 3.现在请记住,您不是在使用JDBC逻辑,在这种情况下,数据库将在基于ORM的框架内处理事务. ORM框架需要事务才能触发对象缓存和数据库之间的同步.因此,您必须了解并为执行ORM逻辑的方法(如deleteByCustomerId)提供事务上下文.Now keep in mind that you aren't working with JDBC logic, in which case the database take care about the transactions, but within a ORM-based framework. ORM frameworks require a transaction in order to trigger the synchronization between the object cache and the database.So you must be aware and provide a transaction context for methods that do ORM logic like deleteByCustomerId.默认情况下,@Transactional(我的意思是没有任何参数)将传播模式设置为REQUIRED,并将readOnly标志设置为false.调用其中注释的方法时,如果不存在任何事务,则会初始化一个事务.这就是为什么@LucasSaldanha的解决方法(与示例使用门面定义多个存储库调用的交易相同)和选项 4 的原因.强>的作品.否则,如果没有交易,您将陷入选项 1 的抛出异常.By default @Transactional (I mean without any parameter) set propagation mode to REQUIREDand readOnly flag to false. When you invoke a method annotated within, a transaction is intialized if no-one exists. This is the reason of why the workaround of @LucasSaldanha (the same as example Using a facade to define transactions for multiple repository calls) and the option 4 works. Other wise, without a transaction, you fall in the thrown exception of the option 1. 这篇关于Spring Boot + Hibernate + JPA没有可用的事务性EntityManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-04 07:02
查看更多