mysql我們在寫sql語句的時候都知道怎麼查找需要的字段,那麼Hibernate怎麼寫呢?
首先看下我們的數據庫表(案例)。
首先我們要知道mysql怎麼寫呢?
例如我們只需要numberId和number
select u.numberId,u.number from number_pool u where u.numberId = 1;
在mysql中運行正確。
mysql我們拿到了需要的字段,那Hibernate怎麼寫呢?
String hql = "select new NumberPool(n.numberId, n.number) from NumberPool n where n.numberId = 1 ";
運行後,咦?報錯了
org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.dkt.entity.NumberPool
at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:369)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.renderSQL(QueryTranslatorImpl.java:653)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:245)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:211)
。。。。。。
這是因爲沒有對應的構造函數。
上面的hql語句中有new NumberPool(n.numberId, n.number)這端代碼,這端代碼其實是創建一個新的NumberPool對象,那麼就需要與此相同的一個構造函數。
上面的錯誤就是告訴你,hibernate沒有找到對應的構造函數。
原因找到了那就添加一個吧。
注意,這個構造函數的參數一定要與你hql中想取得的參數一致。
@Entity
@Table(name = "number_pool")
public class NumberPool {
public NumberPool() {
}
public NumberPool(String numberId, String number) {
this.numberId = numberId;
this.number = number;
}
。。。。。。
}
然後我們再運行,看我們拿到了,這兩個字段,而其他的參數都是null。