如何在Java Spring和Hibernate的单个事务中管理2个DAO方法? [英] How to manage 2 DAO methods in a single transaction in Java Spring and Hibernate?

查看:104
本文介绍了如何在Java Spring和Hibernate的单个事务中管理2个DAO方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个新的动态网站,并在Spring MVC中创建了2个DAO类来管理2个不同表中的查询。
我需要知道如何在单个事务中使用Hibernate管理2个DAO方法...实际上,我创建了2个DAO Java类和相关的实现类:

第一个DAO类(FirstDAOImpl.java):

  @Transactional(readOnly = false,rollbackFor = Exception.class)
public void insertUser(User user)
{
//使用hibernate插入用户...
}
$ b $第二个DAO类(SecondDAOmpl.java):

$ $ p $ @Transactional( rollbackFor = Exception.class)
public void insertUserRole(UserRole register)
{
//使用hibernate插入用户角色...
}

$ b


$ b

实际上,对于任何DAO方法,我都有一个新的交易方法:

  @RequestMapping(value =/ new -user,method = RequestMethod.POST)
public String insertNe wUser(模型模型)
{
//其他代码
尝试
{
firstDAO.insertUser(myUserObject);
secondDAO.insertUserRole(myUserRoleObject);
}
catch(Exception e)
{
logger.info(exception!);
}
//其他代码
}

insertUserRole()插入新记录失败,则前一个方法 insertUser()的事务将成功执行,而不会回滚!

如何在一次交易中管理这两种方法?我会继续分开这两个操作...



谢谢! :)

解决方案

您需要使用 @Transactional

事务将在DAO方法之外创建,并且它们将使用现有事务(由于默认传播)而不是创建它们自己的事务新的。


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.

这篇关于如何在Java Spring和Hibernate的单个事务中管理2个DAO方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆