码迷,mamicode.com
首页 > 数据库 > 详细

一段拼装sql的小代码

时间:2016-06-27 12:02:30      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

/**
     * 单表查询
     * 
     * className:实体类的名字
     * vals:查询的属性
     * pNames:条件的名字
     * pVals:条件的值
     */
    @Override
    public List<Object> get(String className,String[] vals,Object[] pNames,Object[] pVals){
        if(StringUtils.isEmpty(className)) {
            throw new NullParameterException("实体类的名字没有写");
        }
        
        StringBuffer hql = new StringBuffer();
        if(vals.length != 0) { 
            hql.append("SELECT ");
        
            for(int i=0; i<vals.length;i++) {
                hql.append("p.");
                hql.append(vals[i]);
                if(i != vals.length-1) {
                    hql.append(", ");
                }
            }
        }
        hql.append(" FROM ");
        hql.append(className);
        hql.append(" p");
        if(pNames.length>0 && pVals.length>0 && pNames.length==pVals.length) {
            hql.append(" WHERE ");
            for(int i=0;i<pNames.length;i++) {
                hql.append(" p.");
                hql.append(pNames[i]);
                hql.append("=");
                hql.append(pVals[i]);
                if(i<pNames.length-1) {
                    hql.append(" AND ");
                }
            }
        }
        System.out.println(hql.toString());
        return null;
    }
1. userDao.get("VerificationCode", new String[] {"val1","val2"}, new Object[]{"p1","p2","p3"}, new Object[] {"pv1","pv2","pv3"});
输出:SELECT p.val1, p.val2 FROM VerificationCode p WHERE  p.p1=pv1 AND  p.p2=pv2 AND  p.p3=pv3


 2. userDao.get("VerificationCode", new String[] {}, new Object[]{"p1","p2","p3"}, new Object[] {"pv1","pv2","pv3"});

输出: FROM VerificationCode p WHERE  p.p1=pv1 AND  p.p2=pv2 AND  p.p3=pv3

3. userDao.get("VerificationCode", new String[] {}, new Object[]{}, new Object[] {});

  输出:FROM VerificationCode p

 

 4.userDao.get("VerificationCode", new String[] {"p1"}, new Object[]{}, new Object[] {});

 输出:SELECT p.p1 FROM VerificationCode p

 






 

一段拼装sql的小代码

标签:

原文地址:http://www.cnblogs.com/wwzyy/p/5619606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!