鏈接數據庫方法,及反射獲取數據,之前的方法相同,測試類 是在DAO模型下創建的java
--------------------------------------------------------------
customer類:
package com.lanqiao.javatest;mysql
import java.sql.Date;sql
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
}數據庫
public Customer(int id, String name, String email, Date birth) {
super();
this.id = id;
this.name = name;
this.email = email;
this.birth = birth;
}數組
public int getId() {
return id;
}ide
public void setId(int id) {
this.id = id;
}模塊化
public String getName() {
return name;
}函數
public void setName(String name) {
this.name = name;
}測試
public String getEmail() {
return email;
}this
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", birth=" + birth + "]";
}
}
------------------------------------------------------------------------
ReflectionUtils類,實現反射方法:
package com.lanqiao.javatest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* 反射的 Utils 函數集合
* 提供訪問私有變量, 獲取泛型類型 Class, 提取集合中元素屬性等 Utils 函數
* @author Administrator
*
*/
public class ReflectionUtils {
/**
* 經過反射, 得到定義 Class 時聲明的父類的泛型參數的類型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param clazz
* @param index
* @return
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index){
Type genType = clazz.getGenericSuperclass();
if(!(genType instanceof ParameterizedType)){
return Object.class;
}
Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
if(index >= params.length || index < 0){
return Object.class;
}
if(!(params[index] instanceof Class)){
return Object.class;
}
return (Class) params[index];
}
/**
* 經過反射, 得到 Class 定義中聲明的父類的泛型參數類型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static<T> Class<T> getSuperGenericType(Class clazz){
return getSuperClassGenricType(clazz, 0);
}
/**
* 循環向上轉型, 獲取對象的 DeclaredMethod
* @param object
* @param methodName
* @param parameterTypes
* @return
*/
public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
//superClass.getMethod(methodName, parameterTypes);
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
//Method 不在當前類定義, 繼續向上轉型
}
//..
}
return null;
}
/**
* 使 filed 變爲可訪問
* @param field
*/
public static void makeAccessible(Field field){
if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}
/**
* 循環向上轉型, 獲取對象的 DeclaredField
* @param object
* @param filedName
* @return
*/
public static Field getDeclaredField(Object object, String filedName){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
return superClass.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
//Field 不在當前類定義, 繼續向上轉型
}
}
return null;
}
/**
* 直接調用對象方法, 而忽略修飾符(private, protected)
* @param object
* @param methodName
* @param parameterTypes
* @param parameters
* @return
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
Object [] parameters) throws InvocationTargetException{
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if(method == null){
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch(IllegalAccessException e) {
System.out.println("不可能拋出的異常");
}
return null;
}
/**
* 直接設置對象屬性值, 忽略 private/protected 修飾符, 也不通過 setter
* @param object
* @param fieldName
* @param value
*/
public static void setFieldValue(Object object, String fieldName, Object value){
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {
System.out.println("不可能拋出的異常");
}
}
/**
* 直接讀取對象的屬性值, 忽略 private/protected 修飾符, 也不通過 getter
* @param object
* @param fieldName
* @return
*/
public static Object getFieldValue(Object object, String fieldName){
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
System.out.println("不可能拋出的異常");
}
return result;
}
}
---------------------------------------------------------------------------------------------
實現增刪改查的方法類:
package com.lanqiao.javatest;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import com.mysql.jdbc.ResultSetMetaData;
/*
* DAO:Date Access Object:數據庫訪問對象
* 用處:訪問數據信息的類,包含了對數據的增刪改查操做(insect,delect,update,select);
* 而不包含任何業務相關的信息
* 好處:更容易實現功能的模塊化,更容易實現代碼的維護和升級
* 使用jdbc編寫DAO使用的一些方法,
*
* */
public class TestDAO {
//鏈接數據庫
public Connection getConnection() throws Exception{
//四個必要步驟
String driverClass=null;
String jdbcUrl=null;
String user=null;
String password=null;
InputStream in=
TestDAO.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
user=properties.getProperty("user");
password=properties.getProperty("password");
//反射獲取
Driver driver=(Driver) Class.forName(driverClass).newInstance();
Properties info=new Properties();
info.put("user", "root");
info.put("password", "lxn123");
Connection connection=driver.connect(jdbcUrl, info);
return connection;
}
//此時getconnection方法
public void testConnection() throws Exception{
System.out.println(getConnection());
}
//實現delect,update,insect功能
public void update(String sql,Object...args) throws Exception{
//Object...args:可變參數,能夠當數組使用,不用知道他的大小,直接傳就好了
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection=getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
//更新
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
TestDAO.close1(connection, preparedStatement);
}
}
//查詢一條記錄,返回對應的對象
public <T> T getT(Class<T> clazz,String sql,Object...args) throws Exception{
T entity=null;
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
connection=getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
resultSet=preparedStatement.executeQuery();
//ResultSetMetaData能夠得到數據庫的屬性,及其值
ResultSetMetaData rsmd=(ResultSetMetaData) resultSet.getMetaData();
Map <String, Object> values=new HashMap<String, Object>();
while(resultSet.next()){
for(int i=0;i<rsmd.getColumnCount();i++){
String conlumnLabel=rsmd.getColumnLabel(i+1);
Object conlumnValues=resultSet.getObject(conlumnLabel);
values.put(conlumnLabel, conlumnValues);
}
}
if(values.size()>0){
entity=clazz.newInstance();//利用反射獲取的數據
//強制for循環
for(Map.Entry<String, Object> entry: values.entrySet()){
String fieldName=entry.getKey();
Object fieldValues=entry.getValue();
System.out.println(fieldName+":"+fieldValues);
ReflectionUtils.setFieldValue(entity, fieldName, fieldValues);
}
}
} catch (Exception e) {
// TODO: handle exception
}finally {
TestDAO.close(connection,preparedStatement,resultSet);
}
return entity;
}
public <T> List<T> getForList(Class<T> clazz,String sql,Object...args){
return null;
}
// public <T> E getForValues(Class<T> clazz,String sql,Object...args){
//
// return null;
// }
//關閉資源方法
public static void close1(Connection connection,PreparedStatement preparedStatement)
throws Exception{
if (preparedStatement!=null) {
preparedStatement.close();
}if (connection!=null) {
connection.close();
}
}
public static void close(Connection connection,
PreparedStatement preparedStatement,ResultSet resultSet) throws Exception{
if (resultSet!=null) {
resultSet.close();
}
if (preparedStatement!=null) {
preparedStatement.close();
}
if (connection!=null) {
connection.close();
}
}
}
----------------------------------------------------------------
功能的實現類,測試增刪改查:
package com.lanqiao.javatest;
import static org.junit.Assert.*;
import java.sql.Date;
import org.junit.Test;
public class DAOTest { TestDAO dao=new TestDAO(); @Test //改 public void testUpdate() throws Exception { String sql="update customer set name='apanpan' where id=?;"; dao.update(sql, 3); } //查 @Test public void testGetT() throws Exception { String sql="select id,name,email,birth from customer where id=?"; Customer customer=dao.getT(Customer.class, sql, 2); System.out.println(customer); } //增 @Test public void testInsert() throws Exception { String sql="insert into customer(id,name,email,birth) values(?,?,?,?);"; dao.update(sql,"3","panpan","aiqiyi",new Date(new java.util.Date().getTime())); } //刪 @Test public void testDelect() throws Exception{ String sql="delete from customer where id=?"; dao.update(sql, 2); }}