java减少代码书写——数据访问层Wrapper—获取数据及分页—反射2
——————————————使用效果——————————————————


——————————————源码——————————————————
————DButil类,这个类我封装的不好,主要看open(),close(),getResultList(String classpath,String sql,Object... src)这几个方法,主要代码我标红
package com.fendou.DBUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.fendou.myfactory.Myfactory;
import com.fendou.vo.Orders;
import com.fendou.wrapper.IWrapper;
import com.fendou.wrapper.WrapperBatcher;
/**
* DButil类2012-9-13
* @author 牟云飞
*
*/
public class DButil<T> {
private String driver=Myfactory.driver;
private String url=Myfactory.url;
private String user=Myfactory.user;
private String pwd=Myfactory.pwd;
private Connection con =null;
private Statement stat = null ;
private ResultSet rs = null;
private PreparedStatement ps =null;
public DButil(){
}
/**
* 打开数据连接,如果关闭成功,返回true,否则false
* @return boolean
*/
public boolean open(){
boolean flag = false;
try {
Class.forName(driver);
con = DriverManager.getConnection(url,user,pwd);
flag=true;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
/**
* 关闭连接,成功true,失败false
* @return boolean
*/
public boolean close(){
boolean flag = false;
try {
if(rs!=null){
if(rs.isClosed()==false){
rs.close();}
}
if(stat!=null){
if(stat.isClosed()==false){
stat.close();
}
}
if(ps!=null){
if(ps.isClosed()==false){
ps.close();
}
}
if(con!=null){
if(con.isClosed()==false){
con.close();
}
}
flag = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
/**
* 执行sql语句获得list
* 通过iwrapper封装直接得到list
* @param wrapper继承IWrapper<T>
* @param sql语句
* @param src
* @return
*/
public List<T> getResultList(String classpath,String sql,Object... src){
List<T> list = new ArrayList<T>();
//打开连接
open();
try {
ps =con.prepareStatement(sql);
for (int i = 0; i < src.length; i++) {
ps.setObject(i+1,src[i] );
}
//执行,获得result
rs = ps.executeQuery();
//将resultset转换成list
while(rs.next()){
WrapperBatcher<T> w = new WrapperBatcher<T>();
T t = w.setT(classpath, rs);
list.add(t);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//关闭连接
close();
//获得结果
return list;
}
/**
* 执行sql语句返回受影响行数
*增加、删除、修改
* @param sql语句
* @param 参数
* @return 手影响行数
*/
public int update(String sql,Object... src){
int count=0;
//打开连接
open();
try {
ps =con.prepareStatement(sql);
for (int i = 0; i < src.length; i++) {
ps.setObject(i+1,src[i] );
}
//执行,获得受影响行数
count = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//关闭连接
close();
//获得结果
return count;
}
/**
* 执行sql语句返回受影响行数
*增加、删除、修改
* @param sql语句
* @return 手影响行数
*/
public int update(String sql){
int count=0;
//打开连接
open();
try {
ps =con.prepareStatement(sql);
//执行,获得受影响行数
count = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//关闭连接
close();
//获得结果
return count;
}
/**
* 得到连接
* @return Connection
*/
public Connection getConnection() {
return con;
}
/**
* 获取PreparedStatement
* @param sql语句
* @return PreparedStatement
*/
public PreparedStatement getPreparedStatement(String sql){
try {
ps = con.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
/**
* 执行PreparedStatement,获得结果集
* @param PreparedStatement
* @return ResultSet
*/
public ResultSet executePreparedStatement(PreparedStatement pre){
try {
rs = pre.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
/**
* 执行PreparedStatement,获得受影响的行数
* @param PreparedStatement
* @return int
*/
public int executePSUpdate(PreparedStatement pre){
int i = 0;
try {
i = pre.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i;
}
/**
* 开始新的事务
*/
public void openTran(){
if(con!=null){
try {
con.commit();
con.setAutoCommit(false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 提交事务
*/
public void commit()
{
if(con!=null){
try {
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 事务回滚
*/
public void rollback(){
try {
con.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 设置断点
* @param 断点名
* @return
*/
public Savepoint setPoint(String name){
Savepoint s = null;
try {
s = con.setSavepoint(name);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
/**
* 断点回滚
*/
public boolean rollbackByPoint(Savepoint savepoint){
boolean flag = false;
try {
con.rollback(savepoint);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
/**
* 关闭事务
*/
public void closeTran(){
if(con!=null){
try {
con.setAutoCommit(false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//获取statment
public Statement getStatement(){
if(con!=null){
try {
stat = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return stat ;
}
//statement执行
public int executeStatmentUpdate(String sql){
int i = 0;
try {
i = stat.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i ;
}
//用statment返回结果集
public ResultSet executeStatmentQuery(String sql){
try {
rs = stat.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
}
————WrapperBatcher<T>类,这个在DButil类中的getResultLis()方法t中使用
package com.fendou.wrapper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* 2012-9-18
* @author 牟云飞
*
*/
public class WrapperBatcher<T> {
/**
* 方法一:将resultSet自动变成对应的类
* 方法二优秀,方法一再某些条件下是错误的,例如:get、set一旦调用顺序变动
* 都是set
* @param 类的完整路径
* @param resultSet结果集
* @return 对应的类
*/
public T setWrapper(String classPath,ResultSet rs){
T t = null;
try {
Class cl = Class.forName(classPath);
//得到这个类的所有成员
Field[] name = cl.getDeclaredFields();
//得到这个类中所有的方法
Method[] method = cl.getDeclaredMethods();
//实例化
t = (T) cl.newInstance();
//调用set设置值
for(int i =0;i<method.length;i++){
if(method[i].getName().startsWith("set")){
int h =0;
if(((i/2)-1)<=0){
h=0;
}else{
h=i/2-1;
}
String type=name[h].getType().getName();
type = type.substring(type.lastIndexOf(".")+1,type.length());
System.out.println(type+" "+method[i].getName());
if(type.toString().equals("int")){
if(rs.getInt(method[i].getName().toLowerCase().substring(3,method[i].getName().length()))!=0){
method[i].invoke(t,rs.getInt(method[i].getName().toLowerCase().substring(3,method[i].getName().length())));
}else{
method[i].invoke(t,0);
}
}else if(type.toString().toLowerCase().equals("string")){
if(rs.getString(method[i].getName().toLowerCase().substring(3,method[i].getName().length()))!=null){
method[i].invoke(t,rs.getString(method[i].getName().toLowerCase().substring(3,method[i].getName().length())));
}
}else if(type.toString().toLowerCase().equals("date")){
if(rs.getString(method[i].getName().toLowerCase().substring(3,method[i].getName().length()))!=null){
method[i].invoke(t,rs.getDate(method[i].getName().toLowerCase().substring(3,method[i].getName().length())));
}
}else if(type.toString().toLowerCase().equals("double")){
if(rs.getDouble(method[i].getName().toLowerCase().substring(3,method[i].getName().length()))!=0){
method[i].invoke(t,rs.getDouble(method[i].getName().toLowerCase().substring(3,method[i].getName().length())));
}else
{
method[i].invoke(t,0.0);
}
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
/**
* 方法二:将resultSet自动变成对应的类
* 都是set
* @param 类的完整路径
* @param resultSet结果集
* @return 对应的类
*/
public T setT(String classpath,ResultSet rs){
T t = null;
try {
Class classType = Class.forName(classpath);
//得到这个类的所有成员
Field[] name = classType.getDeclaredFields();
//得到这个类中所有的方法
Method[] method = classType.getDeclaredMethods();
//实例化
t = (T) classType.newInstance();
// 获得对象的所有属性
Field fields[] = classType.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
// // 获得和属性对应的getXXX()方法的名字
// String getMethodName = "get" + firstLetter + fieldName.substring(1);
// 获得和属性对应的setXXX()方法的名字
String setMethodName = "set" + firstLetter + fieldName.substring(1);
// // 获得和属性对应的getXXX()方法
// Method getMethod = classType.getMethod(getMethodName,new Class[] {});
// 获得和属性对应的setXXX()方法,使用filed对象的类型
Method setMethod = classType.getMethod(setMethodName,new Class[] { field.getType() });
// // 调用原对象的getXXX()方法:指定调用的对象和方法的参数值列表
// Object value = getMethod.invoke(t, new Object[] {});
// System.out.println(fieldName + ":" + value);
// 调用拷贝对象的setXXX()方法:指定调用的对象和参数值列表(注意必须是Object类型)
String type=field.getType().getName();
type = type.substring(type.lastIndexOf(".")+1,type.length());
if(type.toString().equals("int")){
if(rs.getInt(field.getName())!=0){
setMethod.invoke(t,rs.getInt(field.getName()));
}
}
if(type.toString().equals("String")){
if(rs.getString(field.getName())!=null){
setMethod.invoke(t,rs.getString(field.getName()));
}
}
if(type.toString().equals("Date")){
if(rs.getDate(field.getName())!=null){
setMethod.invoke(t,rs.getTimestamp(field.getName()));
}
}
if(type.toString().equals("Double")){
if(rs.getDouble(field.getName())!=0){
setMethod.invoke(t,rs.getDouble(field.getName()));
}
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}