/** * 条件查询 */ Stringhql="from Uinfo uname:un order by uid"; Queryquery= session.createQuery(hql); // 对cd进行赋值查询 query.setParameter("un","111"); // 获取单条记录使用getSingleResult() Sysusery= (Sysuser)query.getSingleResult();
/** * 查询部分字段 */ Stringhql="select uname,uphone from Uinfo order by uid"; // 或者使用这个 // String hql = "select new Uinfo (uname,uphone) from Uinfo where uid = :uid order by uid"; Queryquery= session.createQuery(hql); List<Object[]> list = query.list();
/** * 查询结果封装为map */ Stringhql="select new map (uname,uphone) from Uinfo where uid = :uid order by uid"; Queryquery= session.createQuery(hql); query.setParameter("uid",24); Map<String,Object> result = (Map<String,Object>)query.getSingleResult();
/** * 多表连接查询 */ // 根据id查询用户,并查询角色 // 左外链接:返回的是对象数组 // 迫切左外连接 fetch:返回是单个对象,持有另外一个对象。两个对象之间做了关联 // 需要在实体类中创建一个为连接查询信息的字段 Stringhql="from Cinfo r left join fetch r.uinfo where r.rid=:rid"; // 或者 // String hql = "select u from Uinfo u left join u.cinfo where u.uid=:uid"; Queryquery= session.createQuery(hql); query.setParameter("uid",24); Sysuserresult= (Sysuser)query.getSingleResult();