文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- DuplicateKeyException异常处理:java向数据库插入数据异
- springboot的UnsatisfiedDependencyException异常问题
- org.springframework.dao.DataIntegrityViolationException
- com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'current_state'
- java中出现这种错误: "error": "Internal Server Error",
- The Tomcat connector configured to listen on port 8888 failed to start
- java.nio.charset.MalformedInputException错误解决
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.geekplus.dao
- Springboot The temporary upload location is not valid
文章目录:
在Java开发中,当你向数据库插入数据时,如果插入的数据违反了唯一约束(如主键或唯一索引),就会抛出DuplicateKeyException
异常。处理这个异常可以帮助你确保数据的唯一性并提供友好的错误提示。下面是如何处理DuplicateKeyException
异常的一般步骤:
1. 捕获DuplicateKeyException
异常
使用try-catch
块来捕获异常。
try {
// 尝试插入数据
yourRepository.save(yourEntity);
} catch (DuplicateKeyException e) {
// 处理异常
System.out.println("插入失败:违反唯一约束");
// 你可以选择抛出自定义异常,记录日志,或者其他处理方式
}
2. 提供友好的错误信息
在捕获到异常后,你可以将异常信息转化为用户友好的提示:
try {
yourRepository.save(yourEntity);
} catch (DuplicateKeyException e) {
throw new CustomException("插入数据失败,记录已存在");
}
3. 记录日志
记录异常信息以便于后续排查问题:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
try {
yourRepository.save(yourEntity);
} catch (DuplicateKeyException e) {
logger.error("插入失败:违反唯一约束", e);
throw new CustomException("插入数据失败,记录已存在");
}
问题报错:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DuplicateKeyException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7' for key 'PRIMARY'
### The error may involve cn.itcast.ssm.mapper.ItemsMapper.addItems-Inline
### The error occurred while setting parameters
### SQL: insert into items(id,name,price,pic,createtime,detail)values(?,?,?,?,?,?)
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7' for key 'PRIMARY'
; SQL []; Duplicate entry '7' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7' for key 'PRIMARY'
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:927)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107
4. 事务处理
如果你的操作包含多个数据库操作,考虑将这些操作封装在一个事务中。如果其中一个操作因DuplicateKeyException
异常失败,可以回滚事务以确保数据的一致性。
@Transactional
public void yourServiceMethod() {
try {
yourRepository.save(yourEntity);
// 其他数据库操作
} catch (DuplicateKeyException e) {
logger.error("插入失败:违反唯一约束", e);
throw new CustomException("插入数据失败,记录已存在");
}
}
5. 自定义异常
为你的应用程序创建自定义异常,可以提高代码的可读性和可维护性。
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
通过上述方式处理DuplicateKeyException
异常,你可以更好地控制数据插入的流程,避免因重复键引发的错误,并提供更好的用户体验。
解决方法:
出现以下异常,com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7' for key 'PRIMARY';说明在数据库中这一列,它是关键字!这个关键字数据库中有,所以出现下面异常;就需要把关键字换成数据库表中没有存在的字。