我试图查看有关使用Hibnerate返回列表的信息,但找不到符合我要求的内容,因此需要一些建议。
我有以下课程
BPDataPK:
public class BPDataPK implements Serializable {
private String id;
private int userProfile;
private Date when;
.....
}
BPData:
public class BPData implements Serializable {
private BPDataPK dataPK;
private Date sessionStart;
...
}
HibernateBPDataDAO:
public class HibernateBPDataDAO extends HibernateDaoSupport implements IBPDataDAO{
....
public BPData[] getSessionBPData(Session session) throws Exception {
/**I need to get a list of BPData that matches the following
1. BPDataPK.id== session.getID;
2. BPDataPK.userProfile == session.getUserProfile;
**3. BPData.sessionStart == session.getSessionStart();**
*/
}
}
如何返回匹配两个主键和非主键的BPData列表?
答案 0 :(得分:1)
您不应该环顾以获取某些信息。相反,您应该阅读reference documentation。
本文档有一整章专门讨论使用HQL查询语言,另一章专门用于标准查询。由于此处有一组固定的标准,因此HQL更适合于该任务:
String hql = "select b from BPData b where b.dataPK.id = :id"
+ " and b.dataPK.userProfile = :profile"
+ " and b.sessionStart = :sessionStart";
Query q = hibernateSession.createQuery(hql);
q.setString("id", session.getID());
q.setInt("profile", session.getUserProfile());
q.setTimestamp("sessionStart", session.getSessionStart()); // or setDate, depending on the type of this field
List<BPData> result = q.list();
答案 1 :(得分:1)
如果你正在使用hibernate的JPA实现,你可以这样做
@Entity
@NamedQuery(
name="findByMyQuery",
queryString="SELECT bpdata FROM BPData bpdata WHERE bpdata.dataPK = :sessionId AND bpdata.userProfile = :userProfile AND bpdata.sessionStart = :sessionStart "
)
public class BPData implements Serializable {
private BPDataPK dataPK;
private Date sessionStart;
...
}
public BPData[] getSessionBPData(Session session) throws Exception {
Query queryFindByMyQuery = entityManager.createNamedQuery("findByMyQuery");
queryEmployeeByFirstName.setParameter("sessionId", session.getID());
queryEmployeeByFirstName.setParameter("userProfile", session.getUserProfile());
queryEmployeeByFirstName.setParameter("sessionStart", session.getSessionStart());
return queryEmployessByFirstName.getResultList().toArray();
}