java - Spring @Transactional(readOnly=true) 恢复属性?

标签 java spring hibernate transactional

只是一个简单的问题,汽车实体持久字段颜色值为红色:

00  @Transactional public class MyBean{...
01    public void test(){
02        Car c = s.find(Car.class,1);
03        c.setColor("blue");
04        test1(c);
05        System.out.println(c.getColor());   
06    }
07    @Transactional(readOnly=true)
08    public void test1(Car c){
09        c.setName("black");
10    }
11  }

假设,我们在 Spring ORM TX-Transactional-Annotation 环境中,具有事务语义和事务范围的持久性上下文。

Console 会打印什么?

  • 红色
  • 蓝色
  • 黑色

最佳答案

假设在调用同一实例的方法和 NESTED 事务传播时启用事务语义: 这取决于持久性上下文的范围。

假设一个事务范围的持久化上下文: black 被打印到控制台。汽车实例是分离的,因为它是在只读事务之外获取的,并且没有合并到只读事务中。在分离的实例上调用 setter 是安全的(就像调用 setColor("blue") 一样。

假设持久性上下文的扩展范围: black 也被打印出来。来自 @Transactional

的 javadoc

如果

A transaction manager which cannot interpret the read-only hint will not throw an exception when asked for a read-only transaction.

来自 JPA 2.0 规范第 2.4.1.2 节派生身份的映射:

The embedded id attributes that correspond to the relationship are treated by the provider as “read only”—that is, any updates to them on the part of the application are not propagated to the database.

但我不是 100% 确定,如果没有抛出异常。由于颜色属性不是嵌入式 ID,因此行为可能会有所不同。

如果事务语义可通过代理获得,请参阅 answer of Adrian Shum

关于java - Spring @Transactional(readOnly=true) 恢复属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12814801/

相关文章:

java - 在 Java 应用程序环境中打开 .rtx 文件?

java - 无法在 Camel 端点中设置 ActiveMQ 目标选项

java - Hibernate - 自动或手动 ID - 在集群环境中

java - 是否可以写一个java类文件然后运行它

Java : Why sometimes we get new object from method instead creating from constructor?

java - Spring 安全: do not require authentication for local request

java - 如果我通过 ApplicationContext getBean 方法检索它,则在非托管 Spring 类中获取一个 bean 实例

java - JPA 无法解析列/IntelliJ

java - java.lang.NoSuchMethodError:org.jboss.logging.Logger.debug Spring 4.3,Hibernate 5.1

c# - 启动时对象初始化的模式