mybatis遇坑记之javabean中设置有参构造方法导致java.sql.SQLException: Invalid value for get Int
1.javabean的形式
1.该javabean为public
2.含有私有属性
3.有构造方法(不能有参数)
4.有get和set方法
2.错误描述:
通过mybatis,可以执行插入操作,但一执行查询就报错,显示Cause: java.sql.SQLException: Invalid value for get Int()
1.因为我在数据库中category_id这一列设置的主键自增,
2.在javabean中的有参构造方法,只为category_name和category_type赋值
/*类目id*/
private Integer categoryId;
/*类目名字*/
private String categoryName;
/*类目编号*/
private Integer categoryType;
public ProductCategory(String categoryName, Integer categoryType) {
this.categoryName = categoryName;
this.categoryType = categoryType;
}
在mybatis执行查询操作时
@Select("select * from product_category")
public List<ProductCategory> getAll();
@Select("select * from product_category where category_id=#{categoryId}")
ProductCategory getOne(Integer categoryId);
mybatis在封装对象时会通过javabean的构造函数创建对象,默认是无参构造函数
,但是因为我们自己写了有参构造函数
,会覆盖无参构造函数,所以导致下面的悲剧…
mybatis在数据库中查到了5条数据,然后根据我们的有参构造的类型,从左往右进行匹配.
我们的有参构造函数是string,integer类型;
然而数据库中查到的数据是
category_id, (int)
category_name,(varchar)
category_id_type,(int)
create_time,
update_time;
int可以赋值给string; 但varchar不能赋值给integer,
所以这里就发生报错,显示类型不匹配;
3.解决办法
- 把构造函数补充完整
public ProductCategory(Integer categoryId, String categoryName, Integer categoryType) {
this.categoryId = categoryId;
this.categoryName = categoryName;
this.categoryType = categoryType;
}
这里 create_time,update_time;是在数据库中设置的,会动态改变,这里不影响
- 不用有参构造函数;
直接把有参构造函数换为无参构造函数就行;
默认使用无参构造方法,nybatis会通过属性名自动为我们的javavbean封装数据
总结:
- javabean中最好不要用有参构造函数,如果要用,那么必须得注意数据中的主键也要作为有参构造的参数;
- int可以直接赋值给string,string不能直接赋值给int