JAVA基礎(chǔ):Hibernate基于外鍵的查詢方法

字號(hào):

在解決這個(gè)問題的時(shí)候搜到了百度上的同樣問題:hibernate中表怎么根據(jù)外鍵查詢 ?
    它的設(shè)計(jì)為:
    我有兩張表:Teacher id(主鍵) name
    Student id(主鍵) name tid(外鍵對(duì)應(yīng)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("查詢學(xué)生時(shí)候出現(xiàn)錯(cuò)誤!");
    return null;
    }finally{
    this.closeSession(session);
    }
    }
    答案為:
    改為:String HQL = "select s.name from Student as s where s.teacher.id ="+teacher.getId();
    考試,大提示采用的是MyEclipse中自動(dòng)生成的代碼:
    Comment表:
    id int primary key,
    ...
    bk_id int not null,
    FOREIGN KEY(BK_Id) REFERENCES book(BK_Id)
    應(yīng)該注意,Hibernate是基于對(duì)象的實(shí)現(xiàn),所以Comment表對(duì)應(yīng)的映射中沒有bk_id,而是變?yōu)閎ook對(duì)象。下面是是基于外鍵的查找方法:
    數(shù)據(jù)訪問層(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;
    }
    }
    //根據(jù)外鍵book來查找對(duì)應(yīng)的評(píng)論
    public List findCommentByBook(Object book) {
    return findByProperty("book", book);
    }
    業(yè)務(wù)邏輯層:
    Book book = new Book();
    book.setBkId(bookId); //只要set 主鍵創(chuàng)建一個(gè)book對(duì)象就可以了,因?yàn)閔ibernate雖然對(duì)應(yīng)是基于book對(duì)象的查找,但是實(shí)際上也只動(dòng)用到bookId這個(gè)屬性,其它屬性對(duì)這不起作用(我理解,歡迎更正)
    List list = dao.findByBook(book);
    ·····