Build a search query with a search criteria in another table using JPA criteria -


i need search states statetable based on given country name (not countryid) in country table should match like sql operator using jpa criteria api (countryid foreign key in statetable name implies).

criteriabuilder criteriabuilder = entitymanager.getcriteriabuilder(); criteriaquery<statetable> criteriaquery = criteriabuilder                                           .createquery(statetable.class); root<statetable>root=criteriaquery.from(statetable.class);  list<predicate>predicates=new arraylist<predicate>();  predicates.add(criteriabuilder           .like(root.<string>get("countryname"), "%"+countryname+"%"));  criteriaquery.where(predicates.toarray(new predicate[0]));  entitymanager.createquery(criteriaquery)              .setfirstresult(first)              .setmaxresults(pagesize)              .getresultlist(); 

how following statement modified fulfill need? (again countryname available in country table , criteria query statetable).

predicates.add(criteriabuilder           .like(root.<string>get("countryname"), "%"+countryname+"%")); 

using jpql tedious, since query needs built multiple search criterion. demonstration/illustration.


the country entity:

@entity public class country implements serializable {     @id     private long countryid;             //<----------------------     @column(name = "country_name")     private string countryname;     @column(name = "country_code")     private string countrycode;     @onetomany(mappedby = "countryid", fetch = fetchtype.lazy)     private set<statetable> statetableset; } 

the statetable entity:

@entity public class statetable implements serializable {     @id     private long stateid;     @column(name = "state_name")     private string statename;     @joincolumn(name = "country_id", referencedcolumnname = "country_id")     @manytoone(fetch = fetchtype.lazy)     private country countryid;                //<------------------------------- } 

you need perform join:

join<statetable, country> country = root.join("countryid"); predicates.add(criteriabuilder.like(country.<string>get("countryname"), "%"+countryname+"%")); 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -