DAO模型设计实现数据的 增,删,改,查方法
连接数据库方法,及反射获取数据,以前的方法相同,测试类 是在DAO模型下建立的
--------------------------------------------------------------
customer类:
package com.lanqiao.javatest;
import java.sql.Date;
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;
}
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 + "]";
}
}
------------------------------------------------------------------------
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);
}
}