今日在使用SSH框架进行数据库检索的时候,突然就出现了这个错误,字段解析失败,经过百度发现几乎所有的网上的同行都在说是由于映射文件与实体类字段不匹配,或者说是hql语句中的字段不匹配,但是,我检查了好多遍,发现根本不是这方面的问题,因为我的字段完全没有错。如果按照数据库中其他字段查询没有任何问题,唯独是按照顾客的ID这一外键查询时就会出现错误
我的数据库表是存在多对一关系的,即一个顾客对应的的订单,顾客的ID作为订单的外键,那么此时在订单的实体类中存在的就是顾客的对象,而不是顾客的ID值,订单实体类代码如下所示:
public class CustomerItem implements java.io.Serializable {
// Fields
private Integer id;
private Customer customer;
private Room room;
private Float customerspend;
private String itemstate;
private Float itempay;
private int staytime;
// Constructors
/** default constructor */
public CustomerItem() {
}
/** full constructor */
public CustomerItem(Customer customer, Room room, Float customerspend, String itemState, Float itemPay,
int staytime) {
this.customer = customer;
this.room = room;
this.customerspend = customerspend;
this.itemstate = itemState;
this.itempay = itemPay;
this.staytime = staytime;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Room getRoom() {
return this.room;
}
public void setRoom(Room room) {
this.room = room;
}
public Float getCustomerspend() {
return this.customerspend;
}
public void setCustomerspend(Float customerspend) {
this.customerspend = customerspend;
}
public String getItemState() {
return this.itemstate;
}
public void setItemState(String itemState) {
this.itemstate = itemState;
}
public Float getItemPay() {
return this.itempay;
}
public void setItemPay(double d) {
this.itempay = (float) d;
}
public int getStaytime() {
return staytime;
}
public void setStaytime(int staytime) {
this.staytime = staytime;
}
这是可以发现,实体类中根本没有顾客的ID值,但是由于Hibernate良好的性能,我们依然可以根据顾客ID进行查询,这时就会返回顾客的对象,再根据顾客的get方法获取各个属性。
我的hql查询语句刚开始是这样的:
public List<CustomerItem> findByProperty(String propertyName, Object value) {
log.debug("finding CustomerItem instance with property: " + propertyName + ", value: " + value);
try {
String queryString = "from CustomerItem as model where model." +propertyName + "=?";
Query queryObject = getCurrentSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
System.out.println("dao..." + re);
throw re;
}
}
}
这时执行查询就会出现上述错误,那么解决办法就是去掉其中的别名,这样就会正确,
String queryString = "from CustomerItem where " +propertyName + "=?";
我个人认为可能是由于实体类中并没有顾客的ID这一属性,如果使用别名的话在实体类中找不到该属性,就会出现上述错误。