SOURABH JAIN
SOURABH JAIN

Reputation: 11

what is the difference between using @Transactional in dao layer and in service layer?

What is the difference between using @Transactional in dao layer and in service layer?

@Transactional
class UserDAO{}

or

@Transactional
class UserService{}

We can put this annotation in both the layers. So what is the difference?

Upvotes: 1

Views: 1085

Answers (2)

Prasad Khode
Prasad Khode

Reputation: 6739

if you add @Transactional annotation at Service layer and you are performing multiple operations on database, then all these operations will be in a single transaction and with that you can make sure that both the operations are commited, if any of them failed then roll back.

For example: There is a case you want to create an Employee and your business rule says that for every Employee you create, you need to create User in your database. In such case we would use Transactional annotation at service layer

@Service
public class EmployeeService {

    ....

    @Transactional
    public int createEmployee(Employee emp) {
        //create Employee
        employeeDao.createEmployee(emp);

        User user = new User();
        // some fileds of employee are used to create a User
        user.setEmployeeId(emp.getEmployeeId());
        ....

        userDao.createUser(user);
        ...
    }
}

Upvotes: 2

Milkmaid
Milkmaid

Reputation: 1754

There is no difference at all. But best practice is use it in Service layer. Cause sometimes you need to make transaction through more than one entity. So if you declare transactions in your dao manually. And you call method from service with two methods from your daos you will have two transactions in one call. And that is something what you don't want.

Upvotes: 1

Related Questions