|
1、当一个sql是查询类型时,返回值一般都是列表,这种情况下,我们通过反射模拟mybatis的查询语句封装
2、核心代码:
public static List<Object> buildListDataBySql(String sql, Class<?> clazz) {
List<Object> resList = new LinkedList<Object>();
Connection conn = DbUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Object obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String methodName = "set" + field.getName().substring(0,1).toUpperCase() +field.getName().substring(1);
Column column = field.getAnnotation(Column.class);
if (null != column) {
if (column.type() == Integer.class) {
Integer value = rs.getInt(field.getName());
Method setMethod = clazz.getDeclaredMethod(methodName,
Integer.class);
setMethod.invoke(obj, value);
} else if (column.type() == String.class) {
String value = rs.getString(field.getName());
Method setMethod = clazz.getDeclaredMethod(methodName,
String.class);
setMethod.invoke(obj, value);
}
} else {
//String类型
String value = rs.getString(field.getName());
Method setMethod = clazz.getDeclaredMethod(methodName,
String.class);
setMethod.invoke(obj, value);
}
}
resList.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}
return resList;
}
3、测试代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sql = "select * from jiudian where 1= 1 ";
String searchText = request.getParameter("name");
if (null != searchText && !"".equals(searchText)) {
sql = sql + " and name like '%" +searchText+ "%'";
}
List<Object> res = DaoUtils.buildListDataBySql(sql, Hotel.class);
response.getWriter().append(res.toString());
}
|
|