Search code examples
javajakarta-eecriteria

Java, CriteriaBuilder, query with optional parameter "where"


I have to rewrite some code, but couldn't find proper information on the Internet. The original part looks like this:

String query = "select * from sublog_type_map_v where 1 = 1";
if (responsibleGroupId != null && responsibleGroupId.length() != 0 && !responsibleGroupId.equals("0")) {
    query += " and responsible_group_id = " + responsibleGroupId;
}
if (categoryId != null && categoryId.length() != 0 && !categoryId.equals("0")) {
    query += " and category_id = " + categoryId;
}
if (typeId != null && typeId.length() != 0 && !typeId.equals("0")) {
    query += " and type_id = " + typeId;
}
if (subtypeId != null && subtypeId.length() != 0 && !subtypeId.equals("0")) {
    query += " and subtype_id = " + subtypeId;
}

And I've proceeded to this code:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query.select(root).where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));

But this "where" should be considered optional using "if" expression, as well as the other three parameters (which I will add later). I have no earthly idea how to do it, could anyone help me out?


Solution

  • I guess this will do the needful -

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
    Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
    query = query.select(root);
    if("some boolean expression") {
        query = query.where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));
    }
    

    Similarily you can handle other conditions inside.