// 简单反射练习
// 传递sql语句,和对象 通过反射封装返回所需要的对象(对象里不包含其他对象)
public <T> List<T> queryData2(Object obj,String sql) throws Exception {
Class clazz = obj.getClass();
List<T> list = new ArrayList<T>();
Connection conn = JdbcConnection.getInstance().getConn();
if(conn == null)
return null;
PreparedStatement pst = null;
ResultSet rs = null;
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData md = rs.getMetaData();// 得到表中所有字段
while(rs.next()) {
// 通过反射实列化一个对象
Object o = Class.forName(clazz.getName()).newInstance();
for (int i = 1; i < md.getColumnCount() + 1; i++) {
// 得到 对象set方法名
String setMethodName = createMethodName("set",md.getColumnName(i));
// 拿到对象属性
Field filed = clazz.getDeclaredField(md.getColumnName(i));
filed.setAccessible(true); // 破坏私有封装
// 判断对象属性名称是什么类型
String nameType = filed.getType().getName();
Method setMetond = parseType(nameType,clazz,setMethodName);
if(md.getColumnType(i) == Types.TIMESTAMP) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(rs.getTimestamp(i) != null){
setMetond.invoke(o, new Object[]{sdf.format(rs.getObject(i))});
}
}else{
// 调用xx对象setXXX方法 并将其参数"xxx"设入到属性当中
if(null != rs.getObject(i)){
setMetond.invoke(o, new Object[]{rs.getObject(i)});
}
}
}
list.add((T)o);
}
rs.close();
pst.close();
conn.close();
return list;
}
/***
* 根据属性名创建对应的方法名
* @param option get||set
* @param fieldName 属性名称
* @return 返回方法名称
*/
private String createMethodName(String option,String fieldName){
String uppName = fieldName.toUpperCase();
String startChar = uppName.substring(0,1);
String methodName = fieldName.replaceFirst(startChar.toLowerCase(), startChar);
methodName = option + methodName;
return methodName;
}
/**
* 设置参数类型
* @param nameType 对象属性的类型
* @param clazz 实体对象
* @param setMethodName 对象set方法
* @return
* @throws Exception
*/
private Method parseType(String nameType,Class clazz,String setMethodName)throws Exception{
Method setMetond = null;
if("int".equals(nameType)){ // clazz.getMethod(方法名称,参数列表类型)
setMetond = clazz.getMethod(setMethodName, new Class[]{int.class});
}else if("java.lang.String".equals(nameType)){
setMetond = clazz.getMethod(setMethodName, new Class[]{String.class});
}else if("float".equals(nameType)){
setMetond = clazz.getMethod(setMethodName, new Class[]{float.class});
}
/*else if("java.util.Date".equals(nameType)){
setMetond = clazz.getMethod(setMethodName, new Class[]{Date.class});
}*/
return setMetond;
}
/**
* 通过反射修改表内容
* @param sql
* @param pstParaList
* @return
* @throws Exception
*/
public int updateData2(String sql, List<Object> pstParaList) throws Exception {
PreparedStatement pst = null;
if(!isStartTrans){
System.out.println("!isStartTrans--->");
m_conn = JdbcConnection.getInstance().getConn();
}
if(m_conn == null){
System.out.println("m_conn == null--->");
return -1;
}
pst = m_conn.prepareStatement(sql);
if(pstParaList != null) {
List list = parseSql(sql);
for (int i = 0;i < pstParaList.size();i++) {
Class clazz = pstParaList.get(i).getClass();
Object o = pstParaList.get(i);
Field[] field = clazz.getDeclaredFields(); // 获得所有属性
for (int k = 0; k < list.size(); k++) {
String getMethodName = createMethodName("get",list.get(k).toString());
Method getMetond = clazz.getMethod(getMethodName,null);
// get方法有返回值的 result=返回的属性值
Object result = getMetond.invoke(o, null);
for(int j = 0;j < field.length;j++){
field[j].setAccessible(true);
String strType = field[j].getType().getName();
if(field[j].getName().toString().equals(list.get(k))){
if("java.lang.String".equals(strType)){
pst.setString(k+1,result.toString());
}else if("int".equals(strType)){
pst.setInt(k+1, Integer.parseInt(result.toString()));
}else if("float".equals(strType)){
pst.setFloat(k+1, Float.parseFloat(result.toString()));
}
}
}
}
if(pst.executeUpdate() < 1) {
pst.close();
return -1;
}
}
}
pst.close();
if(!isStartTrans)
m_conn.close();
return 0;
}
/**
* 解析sql语句需要修改什么内容(sql语句:String sql = "update testoa set name=? , timetest=?, age=? where id=?";字段前必须空格)
* @param sql
* @return
*/
private List parseSql(String sql){
List list = new ArrayList();
String[] str = sql.split("=");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
for(int i=0;i<str.length;i++){
String[] str2 = str[i].split(" ");
if(!"?".equals(str2[str2.length-1]) && !" ".equals(str2[str2.length-1])){
list.add(str2[str2.length-1]);
}
}
return list;
}