hql文のまとめ

2153 ワード

1、inを使用し、in内の集合順に結果を照会する
 
List<Integer> employeeIds = dao.getHibernateTemplate().findByNamedParam("select e.employeeId from Employee e where e.workId in (:teamWorkIds) order by FIELD(e.workId, :teamWorkIds)", "teamWorkIds", teamWorkIds);
 
ここのorder by FIELDに注意
 
2、あるオブジェクトに関連付けられたオブジェクトを挿入結果として取ると、次のような異常が発生する可能性があります.
Hibernate異常:query specified join fetching,but the owner of the fetched association was not present in the select list
 
あなたのfetchの東は、戻るオブジェクトの中に存在する必要があります.存在しない場合はfetchを削除する必要があります.直接joinを使用します.
 
3、重複しない選択
String hql = "select distinct m.project from Milepost m left join  m.project "; 
上のこれは第2条を結びつけて見ます
 
4、groupby使用
select sum(l.costWorktime) from Log l left join l.project p left join l.employee e where p.projectId=? and l.workDate between ? and ? group by e.employeeId order by sum(l.costWorktime)
 
そしてmysqlのbetween彼は閉鎖区間です
 
5.hibernateでcount(distinctリスト1,リスト2)…を使用する.groupbyエラー
 
ネットワーククエリの理由、http://blog.csdn.net/hymer2011/article/details/6588040
hqlには次の2つの制限があります.
HQL(SQL)はselect count(distinct x,y)from xxをサポートしていません.
HQLはselect count(*)from(select distinct x,y from xx)をサポートしていない.
すなわち、HQLはfrom文のサブクエリをサポートしていません
単一のcount(distinct x)をサポートできます
 
その後、このように原生を使用するようになりました.
 
String sql1 = "select count(distinct l.project_id, l.sub_project_id), l.employee_id from tbl_log l where l.work_date between ? and ? and l.employee_id in (:employeeIds) group by l.employee_id order by FIELD(l.employee_id, :employeeIds)";
				return session.createSQLQuery(sql1).setDate(0, fromDate).setDate(1, toDate).setParameterList("employeeIds", employeeIds).list();
select sum(l.costWorktime), DATE_FORMAT(l.workDate, '%Y-%m') from Log l where 1=1 group by DATE_FORMAT(l.workDate, '%Y-%m')