/**
* 自动生成查询方法
*
* @param clazz 传入的持久化类 如:User.class
* @param list 需要查询的属性 如:userId,userName
*
*/
public static void generateSelectDao(Class clazz,List list){
Field[] fs = clazz.getDeclaredFields();
StringBuffer methodBuf = new StringBuffer();
methodBuf.append("/**/n");
methodBuf.append(" * 根据条件查找匹配的"+clazz.getSimpleName()+"列表/n");
methodBuf.append(" * add by 孙钢/n");
methodBuf.append(" */n");
methodBuf.append(" * @param o 查询条件 /n");
methodBuf.append(" * @param start 开始的记录/n");
methodBuf.append(" * @param fetchSize 需要查出的记录数/n");
methodBuf.append(" * @return 查出的集合/n");
methodBuf.append(" *//n");
methodBuf.append("public List get"+clazz.getSimpleName()+"List("+"Map o,int start,int fetchSize){/n");
methodBuf.append("/tStringBuffer hqlBuf = new StringBuffer();/n");
methodBuf.append("/thqlBuf.append(/"select ");
for(int i=0;i<list.size();i++){
if(i!=list.size()-1){
methodBuf.append("t."+list.get(i)+",");
}else{
methodBuf.append("t."+list.get(i)+" ");
}
}
methodBuf.append("/");/n");
methodBuf.append("/thqlBuf.append(/"from "+clazz.getSimpleName()+" t where 1=1 /");/n");
methodBuf.append("/tList paraValues = new ArrayList();/n");
methodBuf.append("/tif(o!=null){/n");
for(int i = 0;i<fs.length;i++){
fs[i].setAccessible(true);
String fieldName = fs[i].getName();
methodBuf.append("/t/tif(o.get(/""+fieldName+"/")!=null){/n");
methodBuf.append("/t/t/thqlBuf.append(/"and t."+fs[i].getName()+" = ? /");/n");
methodBuf.append("/t/t/tparaValues.add(o.get(/""+fieldName+"/"));/n");
methodBuf.append("/t/t}/n");
}
methodBuf.append("/t}/n");
methodBuf.append("/t//根据某个属性排序/n");
methodBuf.append("/thqlBuf.append(/"order by t.*** desc /");/n");
methodBuf.append("/tQuery query = createQuery(hqlBuf.toString());/n");
methodBuf.append("/tfor(int i=0;i<paraValues.size();i++){/n");
methodBuf.append("/t/tquery.setParameter(i,paraValues.get(i));/n");
methodBuf.append("/t}/n");
methodBuf.append("/t//从第start条记录开始,一共fetchSize条记录/n");
methodBuf.append("/tquery.setFirstResult(start).setMaxResults(fetchSize);/n");
methodBuf.append("/treturn query.list();/n");
methodBuf.append("}/n");
System.out.println(methodBuf.toString());
}
自动生成查询dao方法
最新推荐文章于 2024-09-24 11:19:00 发布