如何在hql实体Hibernate Java中使用if语句

vpfxa7rd  于 2022-11-14  发布在  Java
关注(0)|答案(1)|浏览(262)

我想用我的实体创建我的查询hql,我想检查MariaDB中的参数列表是否为空
我有一个实体Java学生,我有一个带有列表的查询参数。

public List<Student> findStudent(Set<Student> listStudent, Date dateReg) {
 return getSession().createQuery("SELECT Student(s.studentId,s.firstname, s.lastname) FROM Student s WHERE s.studentId in (:StudentList) " +
        " AND (s.registerDate =:registerDate) " +
        "  ORDER BY s.lastname ASC" )
.setParameter("registerDate", dateReg)
.setParameterList("StudentList", listStudent)
.list()
}

我想减少这个问题:

public List<Student> findStudent(Set<Student> listStudent, Date dateReg) {
if(listStudent != null) {
return getSession().createQuery("SELECT Student(s.studentId,s.firstname, s.lastname) FROM Student s WHERE s.studentId in (:StudentList) " +
        " AND (s.registerDate =:registerDate) " +
        "  ORDER BY s.lastname ASC" )
.setParameter("registerDate", dateReg)
.setParameterList("StudentList", listStudent)
.list()
} else  {
return getSession().createQuery("SELECT Student(s.studentId,s.firstname, s.lastname) FROM Student s WHERE s.registerDate =:registerDate " +
        "  ORDER BY s.lastname ASC" )
.setParameter("registerDate", dateReg)
.list()
}
}

如何使用Case When创建一个简单的查询。你能帮帮我吗。我的数据库是MariaDB 10

oxalkeyp

oxalkeyp1#

我在猜测一些Query类名称,但我会这样做:

public List<Student> findStudent(Set<Student> listStudent, Date dateReg) {
    String sql = "SELECT Student(s.studentId,s.firstname, s.lastname) FROM Student s WHERE s.registerDate = :registerDate ";

    if (listStudent != null && !listStudent.isEmpty()) {
        sql += "AND s.studentId in (:StudentList) ";
    }

    sql += "ORDER BY s.lastName ASC";

    Query query = getSession().createQuery(sql);
    query.setParameter("registerDate", dateReg);

    if (listStudent != null && !listStudent.isEmpty() {
      //You'll probably need to translate the student list into
      //a list of extracted IDs.
      query.setParameterList("StudentList", listStudent);
    }

    return query.list();
}

相关问题