Hibernate基于外键的查询方法
时间:2011-07-28
我在解决这个问题的时候搜到了百度上的同样问题: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);
·····
|