我在解決這個問題的時候搜到了百度上的同樣問題:hibernate中表怎麼根據外鍵查詢 ??
它的設計為:我有兩張表:Teacher id(主鍵) name Student id(主鍵) name tid(外鍵對應Teacher的id)
public List findStudentByTeacher(Teacher teacher) { try { session = this.openSession(); String HQL = "select s.name from Student as s where s.tid =" teacher.getId(); query = session.createQuery(HQL); return query.list(); } catch (Exception e) { e.printStackTrace(); logs.error("查詢學生時候出現錯誤!"); return null; }finally{ this.closeSession(session); } } |
最優答案為:改為:String HQL = "select s.name from Student as s where s.teacher.id =" teacher.getId();
本人採用的是MyEclipse中自動生成的代碼:
Comment表: id int primary key, ... bk_id int not null, FOREIGN KEY(BK_Id) REFERENCES book(BK_Id) |
應該注意,Hibernate是基於對象的實現,所以Comment表對應的映射中沒有bk_id,而是變為book對象.下面是是基於外鍵的查找方法:
數據訪問層(DAO類):
public List findByProperty(String propertyName, Object value) { log.debug("finding Reply instance with property: " propertyName ", value: " value); try { String queryString = "from Reply as model where model." propertyName "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } }
//根據外鍵book來查找對應的評論 public List findCommentByBook(Object book) { return findByProperty("book", book); } |
業務邏輯層:
Book book = new Book(); book.setBkId(bookId); //只要set 主鍵創建一個book對象就可以了,hibernate雖然對應是基於book對象的查找,但是實際上也只動用到bookId這個屬性,其它屬性對這不起作用(我理解,歡迎更正) List<Comment> list = dao.findByBook(book); ····· |