简体   繁体   中英

How to manage 2 DAO methods in a single transaction in Java Spring and Hibernate?

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! :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM