1. 程式人生 > >JAVA中使用JDBC、反射技術接收實體類列表(物件放入List集合中)

JAVA中使用JDBC、反射技術接收實體類列表(物件放入List集合中)

1)匯入jar包

    

2)配置資料庫資訊,建立連線物件

  public class JdbcUtils {

	// jdbc驅動
	private static String jdbcDriver = "com.mysql.jdbc.Driver";
	// 資料庫地址
	private static String jdbcUrl = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
	// 資料庫賬戶
	private static String username = "root";
	// 資料庫密碼
	private static String password = "123456";
	//註冊資料庫連線驅動
	static{
		try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("載入資料庫連線驅動失敗");
		}

	}

        /*
	 * 獲取資料庫連線
	 */
	public static Connection getConnection(String url, String username, String password) {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
			//獲取連線成功
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("獲取資料庫連線失敗!");
		}
		return conn;
	}
	/*
	 * 關閉資料庫連線
	 */
	public static void closeDb(Connection con , Statement st , ResultSet rs) throws SQLException{
		if(rs != null){
			rs.close();
		}
		
		if(st != null){
			st.close();
		}
		
		if(con != null){
			con.close();
		}
	}

       }     

3)MYSQL資料庫中建立表,插入部分測試資料

       CREATE TABLE `student` (
                `id` varchar(30) DEFAULT NULL,
                `name` varchar(50) DEFAULT NULL,
                `age` int(10) DEFAULT NULL,
                `pic` varchar(50) DEFAULT NULL,
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

              INSERT INTO `student` VALUES ('1', 'lisi', null, null);
              INSERT INTO `student` VALUES ('1', 'zhangsan1', '1', null);
              INSERT INTO `student` VALUES ('2', 'zhangsan2', null, null);

4)建立學生實體類

  public class Student {
	private String id;
	private String name ;
	private Integer age;
	private String pic;
	public String getPic() {
		return pic;
	}
	public void setPic(String pic) {
		this.pic = pic;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

    

5)所用到的方法練習,先看一邊流程

public class ReflectDemo {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		Class clazz = Student.class;
		
		//返回 Field 物件的一個數組,這些物件反映此 Class 物件所表示的類或介面所宣告的所有欄位。
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			System.out.println(field.getName()+"是Student物件中的屬性,型別為"+field.getType());
		}
		
		System.out.println("");
		//返回 Method 物件的一個數組,這些物件反映此 Class 物件表示的類或介面宣告的所有方法,包括公共、保護、預設(包)訪問和私有方法,但不包括繼承的方法。
		Method[] methods = clazz.getDeclaredMethods();
		for (Method method : methods) {
			System.out.println(method.getName()+"是Student中的方法");
		}
		
		System.out.println();
		Object object = clazz.newInstance();
		System.out.println(object.getClass().getName());
		
		Student stu = (Student)object;
		System.out.println(stu.getClass().getName());
	}
}

}

6)程式碼實現

       public static void main(String[] args) throws Exception {
	    Connection conn = getConnection(jdbcUrl, username, password);
	    //使用反射技術將取出資料封裝到物件中
	    reflectDemo(conn,"com.test.Student");
	}
	private static void reflectDemo(Connection conn,String className) throws Exception, IllegalAccessException {
		PreparedStatement ps = conn.prepareStatement("select * from student");
		ResultSet rs = ps.executeQuery();
		ResultSetMetaData data = rs.getMetaData();
		List<Object> resultList = new ArrayList<Object>();
//		System.out.println(data.getColumnCount());
		Class clazz = Class.forName(className);
		while(rs.next()){
			Object obj = clazz.newInstance();
			for (int i = 1; i < data.getColumnCount(); i++) {
				
				String filedName = data.getColumnName(i);
				try{
					//獲取屬性
					Field f = clazz.getDeclaredField(filedName);
					//獲取屬性型別
					Class fieldType = f.getType();
					
					String methodName="set"+filedName.substring(0,1).toUpperCase()+filedName.substring(1);
					
					Method m = clazz.getDeclaredMethod(methodName, fieldType);
					
					Object fieldValue = rs.getObject(filedName);
			
					m.invoke(obj, fieldValue);
				}catch (Exception e){
					continue;
				}
			}
			System.out.println();
			resultList.add(obj);
		}
		System.out.println(resultList);
		
	}

7)輸出結果

[Student [id=1, name=lisi, age=null], Student [id=1, name=zhangsan1, age=1], Student [id=2, name=zhangsan2, age=null], Student [id=3, name=zhangsan3, age=3]]