只是一个简单的问题,汽车实体持久字段颜色值为红色:
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
如果
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/