利用反射机制从DB取数据转化为Entity的全过程

来源:互联网 发布:删除三星预装软件 编辑:程序博客网 时间:2024/05/17 23:53

1.实体类:

package edu.smc.entity;import java.io.Serializable;import java.math.BigDecimal;import java.util.Date;public class DjNsrxx{     private String username;     private Date datetime;     private BigDecimal big;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Date getDatetime() {return datetime;}public void setDatetime(Date datetime) {this.datetime = datetime;}public BigDecimal getBig() {return big;}public void setBig(BigDecimal big) {this.big = big;}     }

2.将结果集转化为实体:

package edu.smc.util;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.math.BigDecimal;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import edu.smc.entity.DjNsrxx;public class ConvertToEntity {         public static List<DjNsrxx> convert(String sqlStr,Map<String,String> showSelectedMap) throws SQLException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {        List<DjNsrxx> djNsrxxs=new ArrayList<DjNsrxx>();         Connection conn= DB.getConnection();             ResultSet rs=DB.getRs(conn, sqlStr);                        Map<String,String> fieldsPairs=new HashMap<String,String>();      Field[] fields = DjNsrxx.class.getDeclaredFields();      for(Field field:fields){      fieldsPairs.put(field.getName(), field.getGenericType().toString());      System.out.println(field.getName()+"    "+field.getGenericType().toString());      }     while(rs.next()){           DjNsrxx djNsrxx=new DjNsrxx();      for (Map.Entry<String, String> m : showSelectedMap.entrySet()) {               String fieldName=m.getValue();               if (fieldsPairs.get(fieldName).equals("class java.lang.String")) {    String fieldVaule=rs.getString(fieldName);//根据类型取值   System.out.println(fieldName);   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   System.out.println("method name = " + methodName);              Method method = djNsrxx.getClass().getMethod(methodName,String.class);       method.invoke(djNsrxx,fieldVaule);       }// 如果类型是Integer    "class java.lang.Integer"            if (fieldsPairs.get(fieldName).equals("class java.lang.Integer")) {    int fieldVaule=rs.getInt(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   System.out.println("method name = " + methodName);              Method method = djNsrxx.getClass().getMethod(methodName, Integer.class);       method.invoke(djNsrxx,fieldVaule);       }// 如果类型是Double  "class java.lang.Double"         if (fieldsPairs.get(fieldName).equals("class java.lang.Double")) { // 如果type是类类型,则前面包含"class ",后面跟类名拿到该属性的gettet方法  Double fieldVaule=rs.getDouble(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   System.out.println("method name = " + methodName);              Method method = djNsrxx.getClass().getMethod(methodName, Double.class);       method.invoke(djNsrxx,fieldVaule);       }// 如果类型是Boolean 是封装类        if (fieldsPairs.get(fieldName).equals("class java.lang.Boolean")) { // 如果type是类类型,则前面包含"class ",后面跟类名拿到该属性的gettet方法    Boolean fieldVaule=rs.getBoolean(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   System.out.println("method name = " + methodName);              Method method = djNsrxx.getClass().getMethod(methodName, Boolean.class);       method.invoke(djNsrxx,fieldVaule);       }         // 如果类型是Date        if (fieldsPairs.get(fieldName).equals("class java.util.Date")) { // 如果type是类类型,则前面包含"class ",后面跟类名拿到该属性的gettet方法  Date fieldVaule=rs.getDate(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   System.out.println("method name = " + methodName);              Method method = djNsrxx.getClass().getMethod(methodName, Date.class);       method.invoke(djNsrxx,fieldVaule);       }        // 如果类型是Short        if (fieldsPairs.get(fieldName).equals("class java.lang.Short")) { // 如果type是类类型,则前面包含"class ",后面跟类名拿到该属性的gettet方法    Short fieldVaule=rs.getShort(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   Method method = djNsrxx.getClass().getMethod(methodName, Short.class);       method.invoke(djNsrxx,fieldVaule);       }     if (fieldsPairs.get(fieldName).equals("class java.math.BigDecimal")) { // 如果type是类类型,则前面包含"class ",后面跟类名拿到该属性的gettet方法   BigDecimal fieldVaule=rs.getBigDecimal(fieldName);//根据类型取值   String methodName="set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);   Method method = djNsrxx.getClass().getMethod(methodName, BigDecimal.class);       method.invoke(djNsrxx,fieldVaule);       }             }     djNsrxxs.add(djNsrxx);     }       return djNsrxxs;         }}


3.DB类

package edu.smc.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import javax.resource.spi.ConnectionManager;import com.mysql.jdbc.Statement;public class DB {public static Connection getConnection(){Connection conn=null; try{Class.forName("com.mysql.jdbc.Driver").newInstance();conn=DriverManager.getConnection("jdbc:mysql://localhost/db","root","root");   }catch(Exception e){   e.printStackTrace();   }   return conn;}public static ResultSet getRs(Connection conn,String sql) {ResultSet rs = null;try {Statement stat = (Statement) conn.createStatement();rs = stat.executeQuery(sql);} catch (SQLException e) {e.printStackTrace();}return rs;}}

4.测试类

import java.lang.reflect.InvocationTargetException;import java.sql.SQLException;import java.util.HashMap;import java.util.List;import java.util.Map;import edu.smc.entity.DjNsrxx;import edu.smc.util.ConvertToEntity;public class Test {    public static void main(String[] args) {String str="select * from testTable";Map<String,String> maps=new HashMap<String, String>();maps.put("用户名", "username");maps.put("时间", "datetime");maps.put("价格", "big");try {List<DjNsrxx> djnsrxxs=ConvertToEntity.convert(str, maps);for(int i=0;i<djnsrxxs.size();i++){DjNsrxx djnsrxx=djnsrxxs.get(i);System.out.println("用户名"+djnsrxx.getUsername());System.out.println("时间"+djnsrxx.getDatetime());System.out.println("价格"+djnsrxx.getBig());}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }}


5.结果

username    class java.lang.Stringdatetime    class java.util.Datebig    class java.math.BigDecimalusernamemethod name = setUsernamemethod name = setDatetimeusernamemethod name = setUsernamemethod name = setDatetimeusernamemethod name = setUsernamemethod name = setDatetimeusernamemethod name = setUsernamemethod name = setDatetime用户名sll时间2012-04-05价格99.999用户名jensen时间2012-04-05价格99.999用户名ll时间2012-04-05价格99.999用户名xx时间2012-04-05价格99.999


 




 

 

原创粉丝点击