java - Criteria Api: Use another parameter in multiselect, if the first one is null -


i have pojo class person has 2 field. lets assume 1 of them holds value , other 1 always null

public class person {      private string music;      private string sports;      ... } 

i want fill either 1 or other list of dtos via criteria api. here snippet of (incomplete) dao code:

criteriabuilder cb = em.getcriteriabuilder(); criteriaquery<persondto> query = cb.createquery(persondto.class); root<person> root= query.from(person.class);  path<string> musicpath = root.get(person_.music); path<string> sportspath= root.get(person_.sports);  query.multiselect(/** todo */);  list<persondto> results = em.createquery(query).getresultlist(); 

is there way use either music oder sports multiselect, depending on of them not null current record. or have define subquery achieve behavior?

you looking coalesce expression (see ch. "query language", paragraph "case expressions" in specification).

create expression returns null if arguments evaluate null, , value of first non-null argument otherwise.

the corresponding criteria api criteriabuilder.coalesce() set of methods. selecting single string simple as:

query.select(cb.coalesce(musicpath, sportspath)); 

if want persondto of course, have make use of criteriabuilder.construct() method and appropriate constructor:

query.select(cb.construct(persondto.class, cb.coalesce(musicpath, sportspath), ...)); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -