1. 程式人生 > >hibernate關聯查詢純SQL的實現(mysql)

hibernate關聯查詢純SQL的實現(mysql)

兩張表關聯查詢,學生表和學生學習記錄表,學生表是學生的基本資訊,學習記錄主要是每天背誦的單詞記錄,包括單詞對錯
的個數
ifnull:如果是空則為...
left join左連線,左表全部顯示,右表沒有匹配欄位顯示空
left join後面一張表的查詢結果,用到哪個欄位查詢哪個欄位,沒必要全部查詢
//班級裡的學生單詞背誦查詢
public List<RecitingStudent> findTotalStudents(int classId, Timestamp start, Timestamp end) {
    Session session = getSessionFactory().getCurrentSession();
String query = "SELECT s.studentId, s.name, ifnull(sum(m.correct_number),0) as correct, ifnull(sum(m.error_number),0) as error from " + "student s " + "LEFT JOIN " + "(SELECT studentId,correct_number,error_number FROM " + "reciting_notes r " + "WHERE r.uploadTime BETWEEN ? AND ?) m "
+ "ON " + "s.studentId = m.studentId " + "where " + "s.classId=? " + "GROUP BY s.studentId"; Query query1 = session.createSQLQuery(query).addScalar("studentId",StandardBasicTypes.INTEGER). addScalar("name",StandardBasicTypes.STRING
). addScalar("correct", StandardBasicTypes.INTEGER). addScalar("error",StandardBasicTypes.INTEGER); query1.setParameter(0, start); query1.setParameter(1, end); query1.setParameter(2, classId); List list = query1.list(); List<RecitingStudent> recitingStudents = new ArrayList<>(); for(Iterator iterator = list.iterator(); iterator.hasNext();){ //每個集合元素都是一個數組,陣列元素列值 Object[] objects = (Object[]) iterator.next(); RecitingStudent recitingStudent = new RecitingStudent(); recitingStudent.setStudentId((Integer) objects[0]); recitingStudent.setName((String) objects[1]); recitingStudent.setCorrect((Integer) objects[2]); recitingStudent.setError((Integer) objects[3]); recitingStudents.add(recitingStudent); } return recitingStudents; }
}