Shahid Ghafoor
Shahid Ghafoor

Reputation: 3103

Spring Transaction Management

In service

@Transactional
public void operation(Stock val) {
    Stock findStock = stockDAO.find(val);
    Product findProduct = productDAO.find(findStock.getProductId());
    Item findItem= itemDAO.find(findProduct.getItemId());
}

Spring open the transaction and close accordingly.

As connection is opened and we are hitting three time to DB , will it cost ? (as connection opened one time)/ OR should we use join ?

Upvotes: 0

Views: 73

Answers (1)

StanislavL
StanislavL

Reputation: 57381

In the code provided there are 3 DB queries. So it's better to define one query and place the logic there but avoid early optimizing.

If the method is not often called it's fine to have 3 DB hits. Optimize real bottlenecks.

There are multiple ways:

  1. You can make it readonly

    @Transactional(readOnly = true)

  2. You can write one query with JOIN and WHERE to hit DB once.

  3. Or may be caching the results will help

Upvotes: 1

Related Questions