【项目问题记录】
一.数据库
表:goods
字段:id | name | price
二.项目代码
2.1 实体类:
@Entity
@Table(name="goods")
public class Goods {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="name")
private String gname;
@Column(name="price")
private Integer gprice;
public Goods(){
}
public Goods(Integer id,String gname,Integer gprice){
this.id = id;
this.gname = gname;
this.gprice = gprice;
}
//getter setter
}
2.2 查询方法
public String getPrice(Session session,String id) {
System.out.println("获取到的id为"+id);
String hql="from Goods where id = "+id;
System.out.println("flag1");
Query query = session.createQuery(hql);
System.out.println("flag2");
Goods good = (Goods)query.uniqueResult();
System.out.println("flag3");
return good.getGname()+":"+String.valueOf(good.getGprice())+"元";
}
三.问题
3.1 问题情况
在getPrice方法执行的过程中,程序卡在query.uniqueResult();不执行了,程序编译未报错。
控制台输出:
获取到的id为1
flag1
flag2
//然后就停止不动了
网上查询的结果大多是说session打开了没关但是无法解决这里的问题。
3.2 问题解决
现在问题成功解决,把Goods实体类带三个形参的构造函数中形参的命名修改为与数据库表字段一致就可以了。即把2.1中代码
public Goods(Integer id,String gname,Integer gprice){
this.id = id;
this.gname = gname;
this.gprice = gprice;
}
修改为
public Goods(Integer id,String name,Integer price){
this.id = id;
this.gname = name;
this.gprice = price;
}
3.3 问题分析
不知道为嘛!!!!!
可能是因为query.uniqueResult();执行之后返回的数据需要实体的构造函数来构造,并且构造函数的形参需要和数据表字段保持一致?
如果真的是这样就是我看书不够仔细了