捕获重复条目异常

You*_*sef 22 java mysql hibernate jpa sqlexception

我怎么能抓住这个例外:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
                                      Duplicate entry '22-85' for key 'ID_CONTACT'
Run Code Online (Sandbox Code Playgroud)

You*_*sef 25

我用春天所以我们解决它 org.springframework.dao.DataIntegrityViolationException

    try {
        ao_history_repository.save(new AoHistory(..));
    }
    catch (DataIntegrityViolationException e) {
        System.out.println("history already exist");
    }
Run Code Online (Sandbox Code Playgroud)

  • 对于遇到此答案的任何人,请谨慎注意 envs with multiple instances 中答案底部的建议。如果我没记错的话(我很可能是这样),如果您的消费服务运行多个实例(例如具有自动缩放组的 AWS EC2),那么您可能会遇到竞争条件,并且最终仍然会导致数据库约束违规抛出。即,“findBy”响应返回“未找到”,但另一个实例在“findBy”后逻辑可以保留该对象之前已保留该对象。 (7认同)

aun*_*low 10

如果您使用的是Java 1.6+,则捕获SQLIntegrityConstraintViolationException

例如

try {
    ps.executeUpdate("INSERT INTO ...");
} catch (SQLIntegrityConstraintViolationException e) {
    // Duplicate entry
} catch (SQLException e) {
    // Other SQL Exception
}
Run Code Online (Sandbox Code Playgroud)

要么

try {
    ps.executeUpdate("INSERT INTO ...");
} catch (SQLException e) {
    if (e instanceof SQLIntegrityConstraintViolationException) {
        // Duplicate entry
    } else {
        // Other SQL Exception
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `无法访问 SQLIntegrityConstraintViolationException 的 catch 块。这个异常永远不会从 try 语句体中抛出 (2认同)

小智 5

我用的是春天。所以捕获 org.springframework.dao.DuplicateKeyException

try{
    ...
} catch (DuplicateKeyException dke) {
    ...
} 
Run Code Online (Sandbox Code Playgroud)