package com.test;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.poi.hssf.record.formula.functions.T;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import com.ams.bo.webapi.dto.Agent;
public class MultiTaskSearch {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Resource(name = "storeFrontDAO")
private Map search() {
String name="公司";
String email="@163";
String invoiceTitle="公司";
int sign=1;
String at="2012-04-26";
Map<String, Object> map=new LinkedHashMap<String, Object>();//保持添加顺序
// Map<String, Object> map=new HashMap<String, Object>();//无固定顺序
map.put("name like", name);
map.put("email like", email);
map.put("invoiceTitle like", invoiceTitle);
map.put("sign =", sign);
map.put("addtime>=", at);
return map;
}
public <T> List<T> dbSearch(Class typeClass,Map<String, Object> map,String orderby) {
String paths[] = { "ams-servlet.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
List<T> TList=null;
String tablename = typeClass.getName().substring(
typeClass.getName().lastIndexOf(".") + 1);
StringBuffer sql=new StringBuffer("select * from ");
sql.append(tablename);
if (map.size()!=0) {
sql.append(" t where 1=1");//后面只需拼接and条件
}
Set<Entry<String, Object>> set=map.entrySet();
Iterator iterator=set.iterator();
for (int i = 0; i < set.size(); i++) {
Map.Entry mapEntry=(Entry) iterator.next();
if (!"".equals(mapEntry.getValue().toString())) {
//模糊匹配
if (mapEntry.getKey().toString().contains("like")) {
// sql.append(" and t."+mapEntry.getKey()+" "+mapEntry.getValue()+" ");
sql.append(" and t."+mapEntry.getKey()+" ‘%"+mapEntry.getValue()+"%‘");
//精确匹配
}else {
// sql.append(" and t."+mapEntry.getKey()+" ‘%"+mapEntry.getValue()+"%‘");
sql.append(" and t."+mapEntry.getKey()+" "+mapEntry.getValue()+" ");
}
}
}
if (null!=orderby&&!"".equals(orderby)) {
sql.append(orderby);
}
System.out.println("SQL:"+sql.toString());
TList=jdbcTemplate.query(sql.toString(),new Object[] {}, new BeanPropertyRowMapper<T> (typeClass));
return TList;
}
public static void main(String[] args) {
MultiTaskSearch mt=new MultiTaskSearch();
Map map=mt.search();
String orderby=" order by addTime desc";
List<Agent> agents=mt.dbSearch(Agent.class, map,orderby);
for (Agent agent : agents) {
System.out.println(agent.getName());
}
System.out.println("****************"+agents.size());
}
}