我目前正在使用MyBatis-Spring集成框架,这就是我从docs中读到的内容:
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);
}
在服务层中转换异常是否可以?
应该怎么做?
在此先感谢您的建议.
我得到的解决方案是捕获服务层中的异常,但创建自己的异常类型,将捕获的异常作为参数.然后,这可以过滤掉实际构造异常时应包含的错误消息类型,并消除对字符串匹配的需要(至少在服务层中).
你接近那里,除了AccountServiceException有一个构造函数,它将Exception e作为参数.我还选择尽早尝试进行所有数据访问,并将其全部包含在一个try / catch中.由于Mapperfactorybean始终将抛出的异常转换为Spring DataAccessExceptions,因此您不必担心在执行数据访问时捕获其他类型的异常.
我毫不犹豫地认为这是一个答案 – 更多的是经验分享,因为我遇到了这个问题并且犹豫不决.