Java JpaRepository 上的 @Transactional

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22200458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:16:20  来源:igfitidea点击:

@Transactional on a JpaRepository

javaspringhibernatejpa

提问by t0mmyw

I'm using a read only database to get some data in to my project. We use Spring v3 with jpa and hibernate

我正在使用只读数据库将一些数据输入到我的项目中。我们使用带有 jpa 和 hibernate 的 Spring v3

Will the following annotation have the effect of making all calls to my repository a read only transaction? Or do I need the annotation on the service layer calling the repository

以下注释是否会使对我的存储库的所有调用都成为只读事务?或者我需要在调用存储库的服务层上的注释

package com.blah.jpa;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly = true)
public interface ServiceToServerRepository extends JpaRepository<ServiceToServerJPA, String> {

}

So we get all the findOne, findAll for free. But any updates should fail as it is a read only transaction

所以我们免费获得了所有的 findOne 和 findAll。但是任何更新都应该失败,因为它是只读事务

采纳答案by Wojtek Owczarczyk

That should basically do it. But I usually opt for marking service-layer artifacts with Transactionalannotation. Anyway, please also check this post for more information of using transactionality together with Spring Data: How to use @Transactional with Spring Data?

基本上应该可以做到。但我通常选择使用Transactional注释标记服务层工件。无论如何,请同时查看此帖子以获取有关将事务性与 Spring Data 一起使用的更多信息:How to use @Transactional with Spring Data?

回答by Niels Bech Nielsen

The readOnly flag only hints that it is sufficient with a read only transaction while calling the method.

readOnly 标志仅提示在调用方法时使用只读事务就足够了。

If you have a nested transaction from your service layer which is not read only, then it would use that one, and you will effectively disregard this annotation.

如果您的服务层中有一个不是只读的嵌套事务,那么它将使用该事务,并且您将有效地忽略此注释。