首先三个架包:
mysql-connector-java-jar
commons-dbcp-1.4jar
commons-pool-1.5.5jar
导进去;
(从上往下一次调用,实现功能)
--------------------------------------------------------------------------------------
Customer类:
package com.lanqioa.javatest;
import java.sql.Date;
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
// TODO Auto-generated constructor stub
}
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;
}
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;
}
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 + "]";
}
}
-------------------------------------------------------------------------------------
反射方法获取数据(供调用)
/**
* 反射的 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;
}
}
========================================================
DAO类:
package com.lanqioa.javatest;
import java.sql.Connection;
import java.util.List;
/*
* 访问数据的DAO接口:
* 里面定义好访问数据表的各种方法
* T:DAO处理的实体类的类型
* */
public interface DAO <T>{
T get(Connection connection,String sql,Object...args) throws Exception;//返回一个T的对象
List<T> getForList(Connection connection,String sql,Object...args);//返回T的一个集合
<E> E getForValues(Connection connection,String sql,Object...args);//返回一个值
void batch(Connection connection,String sql,Object...args);//批量处理的方法
/*
* connection:数据库连接
* sql:sql语句
* args:填充占位符的可变参数
* */
void update(Connection connection,String sql,Object...args);
}
======================================================
jdbcDaoImpl类:
/*
*
* */
public class jdbcDaoImpl<T> implements DAO<T> {
private static final int BeanHandler = 0;
private QueryRunner queryRunner=null;
private Class<T> type;
public jdbcDaoImpl(){
queryRunner=new QueryRunner();
type = ReflectionUtils.getSuperGenericType(getClass());
}
@Override
public T get(Connection connection, String sql, Object... args) throws Exception{
return queryRunner.query(connection, sql,new BeanHandler<T>(type),args);
}
@Override
public List<T> getForList(Connection connection, String sql, Object... args) {
// TODO Auto-generated method stub
return null;
}
@Override
public <E> E getForValues(Connection connection, String sql, Object... args) {
// TODO Auto-generated method stub
return null;
}
@Override
public void batch(Connection connection, String sql, Object... args) {
// TODO Auto-generated method stub
}
@Override
public void update(Connection connection, String sql, Object... args) {
// TODO Auto-generated method stub
}
}
===========================================================
CustomerDao类:
package com.lanqioa.javatest;
public class CustomerDao extends jdbcDaoImpl<Customer>{
}
===========================================================
CustomerDaoTest类:
public class CustomerDaoTest {
TestJDBC t=new TestJDBC();//调用数据库连接池
CustomerDao customerDao=new CustomerDao();
@Test
public void testGet() throws Exception {
Connection connection=null;
try {
connection=t.testBasicDataSource();//调用数据库连接池
String sql="select id,name,email,birth from customer where id=?";
Customer customer=customerDao.get(connection, sql, 36);
System.out.println(customer);
} catch (Exception e) {
e.printStackTrace();
}finally {
close(connection, null, null);
}
}
@Test
public void testGetForList() {
fail("Not yet implemented");
}
@Test
public void testGetForValues() {
fail("Not yet implemented");
}
@Test
public void testBatch() {
fail("Not yet implemented");
}
@Test
public void testUpdate() {
fail("Not yet implemented");
}
public 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();
}
}
}