增删改查集中营

组合查询

要点:

1.函数参数照传

2.判断参数是否为空,不为空则拼上SQL语句

if(name != null && !"".equals(name)){
  querySQL.append(" AND EM.CN LIKE ? ");
}

3.给SQL语句设参数,设一个位置参数初始值,然后做判断,如果不为空,则设上参数,并把位置加1

int pos = 1;

if(name != null && !"".equals(name)){
pst.setString(pos++, "%"+name+"%");
}

完整代码:

public static List findUserByGroup(String erpType, Long orgId, String name, String number, String[] groupName, int begin, int end) throws SystemException{
List result = null;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
StringBuffer querySQL = new StringBuffer();

querySQL.append(" SELECT * ");
querySQL.append(" FROM (SELECT ROWNUM RN, ");
querySQL.append(" EM.USERID USERID, ");
querySQL.append("EM.U_ID SCREENNAME, ");
querySQL.append(" EM.CN FULLNAME ");
querySQL.append(" FROM ECP_USER_MAPPING EM, ");
querySQL.append(" USERS_ORGS UO ");

if(groupName != null && groupName.length >0){
querySQL.append(",USERGROUP UG, ");
querySQL.append(" USERS_USERGROUPS UUG ");
}


querySQL.append("WHERE 1 = 1");
querySQL.append(" AND EM.ERP_TYPE = ? ");
querySQL.append(" AND EM.USERID = UO.USERID ");
querySQL.append(" AND EXISTS (SELECT * FROM ORGANIZATION_ ORG WHERE ORG.ORGANIZATIONID = UO.ORGANIZATIONID ");
querySQL.append(" START WITH ORG.ORGANIZATIONID = ? ");
querySQL.append(" CONNECT BY PRIOR ORG.ORGANIZATIONID = ORG.PARENTORGANIZATIONID) ");

if(name != null && !"".equals(name)){
querySQL.append(" AND EM.CN LIKE ? ");
}


if(number != null && !"".equals(number)){
querySQL.append(" AND EM.U_ID LIKE ? ");
}

if(groupName != null && groupName.length >0){
querySQL.append(" AND uug.userid(+) = em.userid ");
querySQL.append(" AND ug.usergroupid(+) = uug.usergroupid ");
querySQL.append(" AND ( ");
for(int i=0; i<groupName.length; i++){
if(i == 0){
querySQL.append(" ug.NAME = ? ");
} else {
querySQL.append(" OR ug.NAME = ? ");
}
}
querySQL.append(" ) ");
}
querySQL.append(" ORDER BY EM.U_ID, EM.CN ");
querySQL.append(" ) T ");
querySQL.append(" WHERE T.RN BETWEEN ? AND ? ");
System.out.println(querySQL.toString());
try{
conn=getConnection();
pst=conn.prepareStatement(querySQL.toString());
int pos = 1;
pst.setString(pos++, erpType);
pst.setLong(pos++, orgId);
if(name != null && !"".equals(name)){
pst.setString(pos++, "%"+name+"%");
}


if(number != null && !"".equals(number)){
pst.setString(pos++, "%"+number+"%");
}
if(groupName != null && groupName.length >0){
for(int i=0; i<groupName.length; i++){
pst.setString(pos++, groupName[i]);
}
}

pst.setInt(pos++, begin);
pst.setInt(pos++, end);
rs = pst.executeQuery();

result= Util.resultSet2JavaBean(rs, UserInfoBean.class);

}catch(Exception e){
e.printStackTrace();
throw new SystemException(e);
}finally{
close(conn, pst, rs);
}
return result;
}

你可能感兴趣的:(增删改查)