How to use if statement in hql entity hibernate java

Viewed 25

i want to create my query hql with my entite and i want to check if the parameter list is null or not in mariaDb

I have an entity java Student and i have a query parameter with a list.

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()
}

I want to reduce this query :

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()
}
}

how can i create a simple query with case when . Can you help me. My database is MariaDb 10

1 Answers

I'm guessing at some of Query class name, but I'd do something like this:

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();
}
Related