Search code examples
javajpacriteria

JPA Criteria Query: How to select default value for multiSelect


I have a class with 11 field for multiSelect query.

My problem is, currently, I have data for 10 field. One of them is null and will be use in the future.

query.multiselect(
    selection1,
    selection2,
    ...
    selection10
)

So, I create new constructor with 10 field but it make code is smell because too many parameter. I think it better if my multiselect look like:

query.multiselect(
    selection1,
    selection2,
    ...
    selection10,
    selection11 // this should return default null value
)

How can I do this?


Solution

  • CriteriaQuery.multiselect takes a list of Selection objects. The Selection interface is extended by Expression, and you can use CriteriaBuilder.literal to create a constant expression. Or CriteriaBuilder.nullLiteral for the case you want a constant null. So I would try:

    query.multiselect(
        selection1,
        selection2,
        ...
        selection10,
        criteriaBuilder.nullLiteral(String.class) // use the class of the value that
                                                  // will be selected in the future
    )