DataIntegrityViolationException: Error attempting to get column ‘xx‘——DataIntegrityViolationExceptio

x33g5p2x  于2022-06-27 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(156)

一、解决办法

项目中在更新数据库时出现异常,org.springframework.dao.DataIntegrityViolationException,当然如果控制台直接报这个异常问题的解决估计也不至于让我写篇博客。
先说这个异常代表的含义吧:

这个异常的意思就是在更新(update或insert)数据库时,新的数据违反了完整性,例如主键重复,我这里的问题是数据库的id字段未设置自增,默认值也没设,在插入的时候就出现了这个异常,问题的解决很简单,修改数据库id字段为自增字段,完美解决。

出现这个问题的时候应该去查看更新的字段的数据与数据库中对应字段的属性是否有冲突的地方,或者是待更新的数据本身的问题。
DataIntegrityViolationException: Error attempting to get column ‘xx’

项目背景

项目整体采用的是springboot+mybatis 方式。有一次做数据查询的时候。console突然报:DataIntegrityViolationException: Error attempting to get column ‘xx’…异常。起初没在意。以为是xml中的SQL写错了,排查了没问题。百度一下这个报错,说是实体类属性与数据库字段类型不一致引起的,记录一下防止后续在遇到相似问题。

简单写一下出问题的xml及返回值类型:

1 mapper:

<select id="getUserList" paramType="java.lang.Integer" resultType="com.rllc.pcloud.po.UserPo">
    select id,name,date,sign,del from sys_users where id=#{userId}
</select>

2 UserPo:

@Data
public class UserPo{
  private Integer id;
  
  private String name;

  private String password;
  
  // 问题就出在这个有参构造方法中
  public UserPo(String id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    } 
  
}

问题就出在这个有参的构造方法中。而没有无参构造方法。没有无参构造函数时,mybatsi为啥报这个错误呢?此时只有一个包含全部属性的构造函数,mybatis就会找出这些属性对应的值,并实例化一个实体类对象。在找属性对应的值时,mybatis会按照实体类全属性的构造函数的入参顺序,与sql的查询结果对应,如果实体类的属性和sql结果列不能匹配时都会报错。

综上所述,问题定位了,就很好解决:

补上无参构造方法:

public class UserPo{
  private Integer id;
  
  private String name;

  private String password;

  public UserPo(){
  }  

  // 问题就出在这个有参构造方法中
  public UserPo(String id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    } 
}

OK了.

相关文章

微信公众号

最新文章

更多