开发者

Is there a scenario when you would put @Transactional to a method that only retrieves data?

开发者 https://www.devze.com 2023-03-29 03:15 出处:网络
For example this servi开发者_运维百科ce class\' method below: @Transactional public void findDiscountedItems() {

For example this servi开发者_运维百科ce class' method below:

@Transactional
public void findDiscountedItems() {
   List<Item> items = itemDao.findItems();
   List<Item> discountedItems = new ArrayList<Item>();
   for (Item i: items) {
      if (isDiscounted(i))
         discountedItems.add(i);
   }
   return discountedItems;
}

Is there any scenario it would require this method to be @Transactional?


Yes, when you perform several read operations on the database and you care about consistency. You can apply more restrictive transaction isolation level to acquire read locks and avoid problems like phantom reads.

If you run only a single query, mark the transaction as readOnly or even skip the @Transactional altogether.


Well yes, but in that case @Transactional(readOnly=true) would suffice, which can help the DataStore do an efficient batch of work. 'Isolation' is a probably in this case the most important reason for using transactions.

0

精彩评论

暂无评论...
验证码 换一张
取 消