I get your point. And I respect it. In my former comment I forgot a third and quite important aspect: The widely used Spring Framework and its module Spring Data JPA encourage using queries the way I described. Because of their mechanism of generated repositories it is quite easy to implement a query this way:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByDepartmentIn(
@Param("deparment") List<Department> departments,
Sort sort);
}
This repository method generates a Hibernate query and makes providing departments mandatory (empty list returns 0 result, null returns IllegalArgumentException). Spring 5 (with Hibernate 5) made it easy to provide optional departments:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("from User u " +
"where COALESCE(:departments) is null or u.department in (:departments)")
List<User> findAllByOptionalDepartmentIn(
@Param("departments") List<Department> departments,
Sort sort);
}
With Spring 6 (including Hibernate 6) I have to implement it via Criteria API and Custom Repositories, which is more costlier and verbose:
interface CustomizedUserRepository {
List<User> findAllByOptionalDepartmentIn(List<Department> departments, Sort sort);
}
public class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
@Autowired
private EntityManager em;
@Override
public List<User> findAllByOptionalDepartmentIn(
@Param("departments") List<Department> departments,
Sort sort) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cr = cb.createQuery(User.class);
Root<User> root = cr.from(User.class);
if (departments != null && !departments.isEmpty())
cr.select(root).where(root.get("department").in(departments));
return em.createQuery(cr).getResultList();
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long>, CustomizedUserRepository {
}
My point is: The newly released Spring 6 leaves a lot of Spring 5 users asking why and how to migrate their simple queries. That's why I created this issue … and was talking about shady "workaround solutions" 🙂 . |