有一个学生表,一个老师表,1一个老师可以有N个学生,one -to-many关系
如果是这样的话,可以获取老师和其N个学生
String sql = "from com.core.mvc.po.Teacher t where t.name like :name";
但是如果是这样写的话
String sql = "select new com.core.mvc.po.Teacher(t.id,t.name) from com.core.mvc.po.Teacher t where t.name like :name";
就只能获取老师信息,学生信息就不能获取
因为在实际情况下用第二种的情况比较多(考虑SQL优化,不用的字段尽量不select出来),求各位大神帮忙,
象第二种情况,既要考虑性能,又要能查出学生信息,要怎么办?
------解决方案--------------------
可以用这种
public List<Buyer> login(final Buyer buyer) {
// TODO Auto-generated method stub
/*String sql = "from Buyer as b where b.username = ? and b.password = ?";
List<Buyer> list = this.getHibernateTemplate().find(sql,new Object[]{buyer.getUsername(),buyer.getPassword()});
return list;*/
return (List<Buyer>)this.getHibernateTemplate().execute(new HibernateCallback() {
String Hql="from Buyer b where b.username=? and b.password=?";
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
// TODO Auto-generated method stub
List<Buyer> list=new ArrayList<Buyer>();
try {
Query q=session.createQuery(Hql);
q.setString(0, buyer.getUsername());
q.setString(1, buyer.getPassword());
list=q.list();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list;
}
});
}