一段拼装sql的小代码

时间:2021-05-28 14:51:17
/**
* 单表查询
*
* 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 != ) {
hql.append("SELECT "); for(int i=; i<vals.length;i++) {
hql.append("p.");
hql.append(vals[i]);
if(i != vals.length-) {
hql.append(", ");
}
}
}
hql.append(" FROM ");
hql.append(className);
hql.append(" p");
if(pNames.length> && pVals.length> && pNames.length==pVals.length) {
hql.append(" WHERE ");
for(int i=;i<pNames.length;i++) {
hql.append(" p.");
hql.append(pNames[i]);
hql.append("=");
hql.append(pVals[i]);
if(i<pNames.length-) {
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


/**
* 单表更新操作
*
* className:实体类的名字
* uNames:需要更新的字段
* uVals:更新的值
* wNames:条件字段
* wVals:条件值
* */

public int update(String className,Object[] uNames,Object[] uVals,Object[] wNames,Object[] wVals) {
if(StringUtils.isEmpty(className)) {
throw new NullParameterException("实体类的名字没写");
}
StringBuffer hql = new StringBuffer("UPDATE ");
hql.append(className);
hql.append(" p SET ");
if(uNames.length==uVals.length && uNames.length> && uVals.length>) {
for(int i=;i<uNames.length;i++) {
hql.append("p.");
hql.append(uNames[i]);
hql.append("=");
hql.append("'");
hql.append(uVals[i]);
hql.append("'");
if(i<uNames.length-) {
hql.append(",");
}
}
} if(wNames.length==wVals.length && wNames.length> && wVals.length>) {
hql.append(" WHERE ");
for(int i=;i<wNames.length;i++) {
hql.append("p.");
hql.append(wNames[i]);
hql.append("=");
hql.append("'");
hql.append(wVals[i]);
hql.append("'");
if(i<wNames.length-) {
hql.append(" AND ");
}
}
}
// System.out.println(hql.toString());
return sessionFactory.getCurrentSession().createQuery(hql.toString()).executeUpdate();
}