由于缺乏关键词来捕捉这个场景,让我继续描述它。类已被简化。
鉴于这种:
public ItemController {
@Autowired
ItemDtoService ItemDtoService;
@Autowired
DiscountService discountService;
@RequestMapping(value = "/viewItems", method = RequestMethod.POST)
public void process() {
List<ItemDto> ItemDtos = ItemDtoService.getItemDtos();
for(ItemDto i: ItemDtos) {
boolean isDiscounted = discountService.hasDiscount(i); //throws exception here on iteration 2 and the last iteration, ItemDto was discounted
if (isDiscounted) {
i.setPrice(discountService.getDiscountedPrice(i));
//do some other i.setter, basically modify the pojo
}
}
}
}
在以下情况下,discountService.hasDiscount 会引发异常:
- 在随后的迭代中
- 和之前的迭代一样,ItemDto 被打折了。
例外是:
Caused by: org.hibernate.exception.SQLGrammarException: could not update: [somepackage.ItemDto#364]
在堆栈跟踪的某处,您会看到:
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:456)"
问题是方法调用在下面使用了 @Transactional 的 dao 方法(即使它只是一个复杂的查询,也可能有充分的理由)。当 JPA Tx 管理器在方法调用结束时完成其工作时,它会看到 pojo 已修改并尝试同步它。ItemDto pojo 确实有 @Entity,因为在 ItemDtoService.getItemDtos 内部使用 getEntityManager().createNativeQuery(nativeSql, ItemDto.class)。其他 5 个类的详细信息在这里:
@Entity
public class ItemDto{
//body
}
@Service
public class ItemService {
@Autowired
ItemDao itemDao;
public List<ItemDto> getItems() {
return itemDao.getItems(); //for sake of simplicity
}
}
@Repository
@Transactional
public class ItemDaoImpl {
public List<ItemDto> getItems() {
String nativeSql = "select...."
return getEntityManager().createNativeQuery(nativeSql, ItemDto.class);
}
}
@Service
public class DiscountService {
@Autowired
DiscountDao discountDao;
public boolean hasDiscount(ItemDto i) {
boolean hasDiscount = discountDao.hasDiscount(i);
//do other service stuff that might influence the hasDiscount flag
return hasDiscount;
}
}
@Repository
@Transactional
public class DiscountDaoImpl {
public boolean hasDiscount(ItemDto i) {
String nativeSql = "select...."
boolean hasDiscount;
//in reality the query is a complicated joins, executes and returns if has discount or not
return hasDiscount;
}
}
我究竟做错了什么?
我尝试并使用的一些选项包括:
- 将 Dao 方法上的 (readonly=true) 添加到 @Transactional,因为它们只是查询(尽管负面影响是那些可能由于复杂的查询而有意地进行事务处理,并且可能需要锁定以防止脏读)
- 在控制器中,创建一个单独的循环进行修改,然后它有 2 个循环,1 个用于循环遍历项目并查看哪些是打折的,将这些信息存储在某处以便稍后在第二个循环中引用,这会修改所述 pojos
我正在查看其他选项,如果您发现它的编码方式有问题,请发表评论。