简体   繁体   中英

Write Query Using Criteria where parameters are optional

I want to write a hibenrate query using a Criteria where if a parameter is populated it uses that otherwise not.

For instance this table Address Table |Address|Street|Apt|Zip| |sadad | 32 |1 |64112 |adad |12 |4 |64112

now lets say I have a query where I can pass all four rows or none of them. So is there a way to write one query that will retrieve everything populated.I dont want to write multiple queries to check which parameter is populated in request and then retrieve data from tables

why can't you simple check if value is not null in you parameter then add it to Restriction. For example:

Criteria cr = session.createCriteria(Address.class);

if(address != null){
cr.add(Restrictions.eq("address ", address ));
}
if(street!= null){
cr.add(Restrictions.eq("street", street));
}
if(apt != null){
cr.add(Restrictions.eq("apt ", apt ));
}
if(zip != null){
cr.add(Restrictions.eq("zip ", zip ));
}

List results = cr.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM