try {
String queryString = "select count(model) from Client model";
if (map != null) {
boolean bFirst = true;
Object[] obj = null;
for (Object o : map.keySet()) {
if (bFirst) {
queryString += " where ";
bFirst = false;
} else {
queryString += " and ";
}
obj = (Object[]) map.get(o);
if ("1".equals(obj[1].toString())) {
// 模糊查詢
queryString += " model." + o + " like :_" + o;
} else {
// 准確查詢
queryString += " model." + o + "=:_" + o;
}
}
}
Query query = getEntityManager().createQuery(queryString);
try {
String queryString = "select count(model) from Client model";
if (map != null) {//map中是條件
boolean bFirst = true;
Object[] obj = null;
for (Object o : map.keySet()) {
if (bFirst) {//如果是第一個條件,則需要拼接where,如果不是第一個,則是拼接and
queryString += " where ";
bFirst = false;
} else {
queryString += " and ";
}
obj = (Object[]) map.get(o);
if ("1".equals(obj[1].toString())) {//如果是模糊查詢是like,精確查詢時等號
// 模糊查詢
queryString += " model." + o + " like :_" + o;
} else {
// 准確查詢
queryString += " model." + o + "=:_" + o;
}
}
}
也就是比如
map.put("field1",new String[]{"a","1"})
map.put("field2",new String[]{"b","0"})
則,原來SQL是
select count(model) from Client model
在field1的時候需要拼接where
select count(model) from Client model where
然後是1,則是模糊查詢,拼接成
select count(model) from Client model where model.field1 like:_field1
到field2的時候,不是第一個條件,拼接and
select count(model) from Client model where model.field1 like:_field1 and
然後是0,精確查詢
select count(model) from Client model where model.field1 like:_field1 and model.field2 =:_field2