有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java MyBatis映射器直接注入服务类。例外情况如何?

我目前正在使用MyBatis Spring集成框架,这是我从文档中读到的:

Rather than code data access objects (DAOs) manually using SqlSessionDaoSupport or SqlSessionTemplate, Mybatis-Spring provides a proxy factory: MapperFactoryBean. This class lets you inject data mapper interfaces directly into your service beans. When using mappers you simply call them as you have always called your DAOs, but you won't need to code any DAO implementation because MyBatis-Spring will create a proxy for you.

这是一个非常好的功能。。。但是异常处理呢?我应该在哪里翻译SQL错误?在我的服务层?但它不会违反服务DAO模式吗

例如:

public final class AccountServiceImpl implements AccountService {
(...)
    private AccountMapper accountMapper;
(...)
    @Override
    public void addAccount(Account account) throws AccountServiceException {

       //Validating, processing, setting timestamps etc.
       (...)

       //Persistence:
       int rowsAffected;
       try {
            rowsAffected = accountMapper.insertAccount(account);
       } catch (Exception e) {
            String msg = e.getMessage();
            if (msg.contains("accounts_pkey"))
                throw new AccountServiceException("Username already exists!");
            if (msg.contains("accounts_email_key"))
                throw new AccountServiceException("E-mail already exists!");
            throw new AccountServiceException(APP_ERROR);
       }

       LOG.debug("Rows affected: '{}'", rowsAffected);

       if (rowsAffected != 1)
            throw new AccountServiceException(APP_ERROR);
    }

在服务层转换异常可以吗

应该怎么做

提前谢谢你的建议


共 (2) 个答案

  1. # 1 楼答案

    将MyBatis抛出的低级DataAccessException转换为服务层中应用程序定义的异常是一种标准做法

    它通常与事务处理有关,因为您无法在DA层处理跨越多个DAO的事务

    所以是的,这是可以的,甚至是推荐的

    通常,我将DAO引发的异常记录在错误日志中,并重新提交应用程序定义的内容

  2. # 2 楼答案

    最近在一个项目中使用mybatis spring,我遇到了同样的障碍。我也不想让我的服务类与DAO异常处理混为一谈,尤其是因为我的服务层中的一些方法需要对许多不同的表进行只读访问

    我找到的解决方案是在服务层捕获异常,但创建自己的异常类型,将捕获的异常作为参数。这样就可以过滤出在实际构造异常时应该包含什么样的错误消息,并消除对字符串匹配的需求(至少在服务层)

    你很接近于这一点,除了AccountServiceException会有一个以Exception e为参数的构造函数。我还选择尽可能早地尝试访问所有数据,并将其打包在一个try/catch中。由于MapperFactoryBean总是将抛出的异常转换为Spring DataAccessExceptions,因此在进行数据访问时,您不必担心捕获其他类型的异常

    我不愿意考虑这是一个答案-更多的经验分享,因为我遇到了,也犹豫了。p>