一段拼装sql的小代码
时间:2021-07-01 10:21:17
帮助过:3人阅读
*
* 单表查询
*
* 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的小代码
标签: