项目场景:

关于使用 DBUtils数据库 连接池使用查询语句出现的错误


问题描述:

当写好测试类时准备测试查询时出现了这个错误,

java.sql.SQLException: Cannot create com.ishop.pojo.Goods: com.ishop.pojo.Goods Query: select `id`,`sname`,`information`, `brand`, `img_path`, `sales`, `stock` from t_goods where `id` = ? Parameters: [4]

然后在语句在mysql中能正常运行,说明sql语句没有错误

使用dbutils时出现cannot create xxx query情况解决_查询语句
在dao中写好测试类准备测试,发现出现了如上错误

实体类如下

public class Goods {
    private Integer id;          //商品编号
    private String sname;        //商品名

    public Goods(Integer id, String sname) {
        this.id = id;
        this.sname = sname;
    }
    //省略Getter 和 Setter 方法
    //省略toString方法
}

原因分析:

使用QueryRunner类的query方法时,传入的JavaBean类没有无参构造


解决方案:

原因:queryRunner.query(connection, sql, new BeanListHandler(type), args);
使用 new BeanHandler 还有 new BeanListHandler 时 ,传入的实体类加入无参构造即可

(1)里面的属性要有set方法

(2)类里面如果有带参数的改造方法,必须添加一个没有参数的构造方法

(3)查询语句sql = select id, sname, information, brand, img_path, sales, stock from t_goods where id = ?; 里面的参数保证类里面有同名的构造方法;

正确代码

public class Goods {
    private Integer id;          //商品编号
    private String sname;        //商品名

	public Goods(){}	//空构造

    public Goods(Integer id, String sname) {
        this.id = id;
        this.sname = sname;
    }
    //省略Getter 和 Setter 方法
    //省略toString方法
}