How to manage 2 DAO methods in a single transactio

2019-02-18 19:07发布

问题:

I'm building a new dynamic website and I created 2 DAO class in Spring MVC to manage the query in 2 different tables. I need to know how can i manage 2 DAO methods in a single transaction, using Hibernate...Pratically, I create 2 DAO Java classes and related implementation class:

First DAO class (FirstDAOImpl.java):

@Transactional(readOnly = false, rollbackFor=Exception.class)
public void insertUser(User user) 
{
    //do insert an user using hibernate...
}   

Second DAO class (SecondDAOImpl.java):

@Transactional(rollbackFor=Exception.class)
public void insertUserRole(UserRole register) 
{
    //do insert user role using hibernate...
}

In my Spring controller, i need to call both DAO method in a single transaction...

Actually, I have a new transactional method for any DAO method:

@RequestMapping(value = "/new-user", method = RequestMethod.POST)
    public String insertNewUser(Model model) 
    {
        //Other code
        try
        {
            firstDAO.insertUser(myUserObject);
            secondDAO.insertUserRole(myUserRoleObject);
        }
        catch(Exception e)
        {
            logger.info("exception!");
        }
        //Other code
    }

When the method insertUserRole() to insert a new record fails, the transaction for the previous method insertUser() is executed succesfully without rollback!

How can I manage these 2 methods in a single transaction? I would keep separates these 2 operations...

Thanks! :)

回答1:

You need to call the DAO methods from another method with @Transactional.

The transaction will then be created outside of the DAO methods, and they will use the existing transaction (due to the default propagation) instead of creating their own new ones.