一个查询方法public ArrayList<TieUser> getAllReplyTie(int tieId) {
Session session=HibernateUtil.openSession();
Transaction ts=session.beginTransaction();
Query query=session.createSQLQuery("" +
"select u.headImg as headImg,r.replyDate as date from y_reply as r " +
"left join y_user as u on r.userId=u.id where r.tieId=?");
query.setInteger(0,tieId);
System.out.println("query:"+query);
ts.commit();
return new ArrayList<TieUser>(query.list());
}
其中,返回的TieUser是实体类,不对应表public class TieUser {
private String title;
private String name;
private String email;
private String headImg;
private String content;
private int userId;
private String date;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
/*...*/
问题:运行后总是报java.sql.SQLException: Column 'replyDate' not found.
难道这样写不行吗?y_reply中有replyDate这个字段的,其对应的映射文件也有hibernatequerysession
Session session=HibernateUtil.openSession();
Transaction ts=session.beginTransaction();
Query query=session.createSQLQuery("" +
"select u.headImg as headImg,r.replyDate as date from y_reply as r " +
"left join y_user as u on r.userId=u.id where r.tieId=?");
query.setInteger(0,tieId);
System.out.println("query:"+query);
ts.commit();
return new ArrayList<TieUser>(query.list());
}
其中,返回的TieUser是实体类,不对应表public class TieUser {
private String title;
private String name;
private String email;
private String headImg;
private String content;
private int userId;
private String date;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
/*...*/
问题:运行后总是报java.sql.SQLException: Column 'replyDate' not found.
难道这样写不行吗?y_reply中有replyDate这个字段的,其对应的映射文件也有hibernatequerysession
然后你也应该会得到同样的错误!
使用createSQLQuery(原生态)sql查询时、Hibernate就不会在去查找映射、帮你翻译了!
你sql中的字段名称必须跟数据库字段对应!
而不是java程序中实体类的属性名称!
"select r.replyContent as content,r.replyName as name,u.headImg as headImg,r.replyDate as date from y_reply as r " +
"left join y_user as u on r.userId=u.id where r.tieId=?").addScalar("date",Hibernate.STRING)
.addScalar("content",Hibernate.STRING).addScalar("name",Hibernate.STRING);通过这种倒是可以,不过很是麻烦啊