使用dbutils時出現cannot create xxx query情況解決
阿新 • • 發佈:2021-07-29
專案場景:
關於使用 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語句沒有錯誤
在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
使用 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方法
}