2 u012394740 u012394740 于 2015.06.06 18:43 提问

在Struts中这段查询怎么解释

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);

2个回答

danielinbiti
danielinbiti   Ds   Rxr 2015.06.06 23:02
已采纳
 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
happy100happy
happy100happy   2015.06.06 19:20

根据你传入的参数,进行查询。map里面就是存的Client类的属性(ket)和值(value)

Csdn user default icon
上传中...
上传图片
插入图片