如何使用mybatis异常翻译器将mybatis异常映射到spring?

时间:2017-02-20 17:09:16

标签: java spring mybatis spring-mybatis

我读了spring-doc#orm-exception-translation,然后添加2个bean。

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.mybatis.spring.MyBatisExceptionTranslator">
    <constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
    <constructor-arg type="boolean" value="false"/>
</bean>

另外,我的dao由@Repository注释。

@Repository
public class AuthorDaoImpl implements AuthorDao {
    private SqlSessionTemplate template;
    private MultiMapper mapper;

    @Autowired
    public AuthorDaoImpl(SqlSessionTemplate template, MultiMapper mapper) {
        this.template = template;
        this.mapper = mapper;
    }

    @Override
    public void add(Author author) {
        mapper.insertAuthor(author);
    }

    @Override
    public Author getById(int id) {
        return mapper.selectAuthorById(id);
    }

    @Override
    public Author getByName(String username) {
        return mapper.selectAuthorByName(username);
    }

    @Override
    public void update(Author author) {
        mapper.updateAuthor(author);
    }

    @Override
    public void delete(Author author) {
        mapper.deleteAuthor(author);
    }
}

但是当我尝试添加相同的数据时,我得到的仍然是mysql异常。有人可以给我一些想法吗?非常感谢你!

### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'obama' for key 'username'

0 个答案:

没有答案