1. 程式人生 > >出現“org.hibernate.QueryException: could not resolve property”錯誤的解決,針對多對一的表的結構

出現“org.hibernate.QueryException: could not resolve property”錯誤的解決,針對多對一的表的結構

今日在使用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這一屬性,如果使用別名的話在實體類中找不到該屬性,就會出現上述錯誤。