Java基礎--JDBC-反射等

Two手揣兜發表於2016-11-16

User類

package com.JDBCTest;

import java.util.Date;

public class User {

	private Integer id;
	private String username;
	private String address;
	private Date birthday;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

介面類

package com.JDBCTest;

import java.sql.ResultSet;
import java.sql.SQLException;

@FunctionalInterface
public interface ResultSetExtractor {
	
	//函式泛型
	public  Object extractData(ResultSet rs) throws SQLException; 
}


反射類

package com.JDBCTest;

import java.lang.reflect.Method;
import java.util.Date;

public class ReflectUtil {
   
	/**
	 * 設定物件的引數
	 */
	public static void setValue(String name,Object value,Object obj){
		try {
			Class clz = obj.getClass();
			String tname = value.getClass().getTypeName();
			Method method = clz.getDeclaredMethod("set"+name, Class.forName(tname));
			method.invoke(obj, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	public static void main(String[] args) {
//		User user = new User();
//		ReflectUtil.setValue("Id", "7", user);
//		ReflectUtil.setValue("Username", "tt", user);
//		ReflectUtil.setValue("Address", "上海", user);
//	}
 
}

實現類

package com.JDBCTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class Session {

	private static final String url = "jdbc:mysql://119.254.106.50:3309/test?useUnicode=true&characterEncoding=utf8";
	private static final String user = "rw_all_db";
	private static final String password = "rw_all_db";
	
	/**
	 * 獲取單條資料
	 */
	public <T>T query(String sql,ResultSetExtractor extractor){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(url, user, password);
			PreparedStatement statement = connection.prepareStatement(sql);
			ResultSet rs = statement.executeQuery();
			rs.next();
			return (T)extractor.extractData(rs);
		} catch (Exception e) {
			return null;
		} finally {
			//關閉連線
		}
	}
	
	/**
	 * 帶引數獲取單條資料
	 */
	public <T>T query(String sql,ResultSetExtractor extractor,Object...params){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(url, user, password);
			PreparedStatement statement = connection.prepareStatement(sql);
			if(params!=null && params.length > 0){
				for (int i = 0; i < params.length; i++) {
					Object object = params[i];
					statement.setObject(i+1, object);
				}
			}
			ResultSet rs = statement.executeQuery();
			rs.next();
			return (T)extractor.extractData(rs);
		} catch (Exception e) {
			return null;
		}
	}
	
	
	/**
	 * 帶引數獲取多條資料
	 */
	public <T>List<T> queryList(String sql,ResultSetExtractor extractor,Object...params){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(url, user, password);
			PreparedStatement statement = connection.prepareStatement(sql);
			if(params!=null && params.length > 0){
				for (int i = 0; i < params.length; i++) {
					Object object = params[i];
					statement.setObject(i+1, object);
				}
			}
			ResultSet rs = statement.executeQuery();
			List<T> lists = new ArrayList<>();
			while (rs.next()) {
				lists.add((T)extractor.extractData(rs));
			}
			return lists;
		} catch (Exception e) {
			return null;
		}
	}
	
	
	/**
	 * 反射
	 */
	public <T>List<T> queryList(String sql,Class clz,Object...params){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			//獲取連線物件
			Connection connection = DriverManager.getConnection(url, user, password);
			//執行預處理物件
			PreparedStatement statement = connection.prepareStatement(sql);
			//設定引數
			if(params!=null && params.length > 0){
				for (int i = 0; i < params.length; i++) {
					Object object = params[i];
					statement.setObject(i+1, object);
				}
			}
			//結果集
			ResultSet rs = statement.executeQuery();
			//拿到獲取sql語句 select ***from 這段的列明
			ResultSetMetaData metaData = rs.getMetaData();
			int count = metaData.getColumnCount();
			//定義個集合儲存這些列名
			LinkedList<String> colunmNames = new LinkedList<>();
			for (int i = 0; i < count; i++) {
				colunmNames.add(metaData.getColumnName(i+1));//解析儲存
			}

			//定義容器,裝載資料
			List<T> lists = new ArrayList<>();
			while (rs.next()) {
				//例項化物件
				T obj = (T)clz.newInstance();
				for (String string: colunmNames) {
					//講資料庫對應的列明轉換成javabean中對應的屬性名,首字母轉大寫,因為setUsername
					//columnToProperty()講資料庫列名轉換成駝峰命名規則,create_time ---createTime
					//create_time --columnToProperty--createTime--toUpperCaseFirst---CreateTime
					String colunmName = string.substring(0, 1).toUpperCase() + string.substring(1);
					//呼叫反射,給屬性賦值
					ReflectUtil.setValue(colunmName, rs.getObject(colunmName), obj);
				}
				//將資料放入集合中
				lists.add(obj);
			}

			return lists;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void main(String[] args) {
		Session session = new Session();
		//測試一:單條資料
//		String sql = "select id,username,address from user where id = 1";
//		User user1 = session.query(sql, new ResultSetExtractor() {
//			
//			@Override
//			public User extractData(ResultSet rs) throws SQLException {
//				User user = new User();
//				user.setId(rs.getInt("id"));
//				user.setUsername(rs.getString("username"));
//				user.setAddress(rs.getString("address"));
//				return user;
//			}
//		});
//		System.out.println(user1.getId()+"=>"+user1.getAddress()+"=>"+user1.getUsername());
		
		//測試二:帶引數單條資料
//		String sql = "select id,username,address from user where id = ?";
//		User user1 = session.query(sql, new ResultSetExtractor() {
//			
//			@Override
//			public User extractData(ResultSet rs) throws SQLException {
//				User user = new User();
//				user.setId(rs.getInt("id"));
//				user.setUsername(rs.getString("username"));
//				user.setAddress(rs.getString("address"));
//				return user;
//			}
//		},5);
//		System.out.println(user1.getId()+"=>"+user1.getAddress()+"=>"+user1.getUsername());
		
		//測試三:帶引數多條資料
		String sql = "select id,username,address from user where address = ?";
//		List<User> list = session.queryList(sql, new ResultSetExtractor() {
//			
//			@Override
//			public User extractData(ResultSet rs) throws SQLException {
//				User user = new User();
//				user.setId(rs.getInt("id"));
//				user.setUsername(rs.getString("username"));
//				user.setAddress(rs.getString("address"));
//				return user;
//			}
//		},"北京");
//		
//		for (User user1 : list) {
//			System.out.println(user1.getId()+"=>"+user1.getAddress()+"=>"+user1.getUsername());
//		}

		//lamad函式改寫
//		List<User> list1 = session.queryList(sql, (rs) -> {
//				User user = new User();
//				user.setId(rs.getInt("id"));
//				user.setUsername(rs.getString("username"));
//				user.setAddress(rs.getString("address"));
//				return user;}
//		,"北京");
//		
//		for (User user1 : list1) {
//			System.out.println(user1.getId()+"=>"+user1.getAddress()+"=>"+user1.getUsername());
//		}
		
		//反射測試
		List<User> list = session.queryList(sql,User.class,"上海");
		for (User user1 : list) {
		System.out.println(user1.getId()+"=>"+user1.getAddress()+"=>"+user1.getUsername());
	}
  }
}



相關文章