mysql dao封装_利用泛型封装DAO层(万能DAO)

利用泛型封装DAO层(万能DAO)

利用泛型封装DAO层(万能DAO)

package com.cdsxt.base;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.util.ArrayList;

import java.util.List;

import com.cdsxt.po.Person;

import com.cdsxt.util.DBUtil;

//泛型方法

public class BaseDao2 {

//传入po 根据po的值 返回匹配的list

public static List queryList(String sql,Object[] params,T t){

Class clazz=t.getClass();

Connection conn=null;

PreparedStatement ps=null;

ResultSet rs=null;

List list=new ArrayList();

try {

conn=DBUtil.getConn();

ps=conn.prepareStatement(sql);

//填坑

if(params!=null&¶ms.length>0){

for(int i=0;i

ps.setObject(i+1, params[i]);

}

}

rs=ps.executeQuery();

ResultSetMetaData metaData=rs.getMetaData();

int count=metaData.getColumnCount();

while(rs.next()){

T temp=(T)clazz.newInstance();

for(int i=0;i

String fieldName=metaData.getColumnName(i+1);

Field field=clazz.getDeclaredField(fieldName);

Method method=clazz.getMethod(getSetter(fieldName), field.getType());

method.invoke(temp, rs.getObject(i+1));

}

list.add(temp);

}

} catch (Exception e) {

e.printStackTrace();

}finally{

DBUtil.close(rs,ps,conn);

}

return list;

}

//根据id查询po

public static T queryPo(String sql,int id,T t){

Class clazz=t.getClass();

Connection conn=null;

PreparedStatement ps=null;

ResultSet rs=null;

T obj=null;

try {

conn=DBUtil.getConn();

ps=conn.prepareStatement(sql);

ps.setInt(1, id);

rs=ps.executeQuery();

ResultSetMetaData metaData=rs.getMetaData();

int count=metaData.getColumnCount();

obj=(T)clazz.newInstance();

while(rs.next()){

for(int i=0;i

String fieldName=metaData.getColumnName(i+1);

Field field =clazz.getDeclaredField(fieldName);

Method method=clazz.getMethod(getSetter(fieldName), field.getType());

method.invoke(obj, rs.getObject(i+1));

}

}

} catch (Exception e) {

e.printStackTrace();

}finally{

DBUtil.close(rs,ps,conn);

}

return obj;

}

public static void changePo(String sql,Object[] params,Class clazz){

Connection conn=null;

PreparedStatement ps=null;

try {

conn=DBUtil.getConn();

ps=conn.prepareStatement(sql);

//填坑

if(params!=null&¶ms.length>0){

for(int i=0;i

ps.setObject(i+1, params[i]);

}

}

ps.execute();

} catch (Exception e) {

e.printStackTrace();

}finally{

DBUtil.close(ps,conn);

}

}

public static String getSetter(String fieldName){

//传入属性名 拼接set方法

return “set”+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);

}

public static void main(String[] args) {

// List list=BaseDao2.queryList(“select * from person “, null, new Person());

// System.out.println(list.size());

Person person=queryPo(“select * from person where id=?”,4,new Person());

System.out.println(person.getName());

}

}

后面的main()方法为测试用,用的时候将其删除即可

2.DBUtil类:

package com.cdsxt.utils;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Properties;

public class DBUtil {

private static String mysqlDriver;

private static String url;

private static String user;

private static String password;

static{

try {

InputStream is=DBUtil.class.getResourceAsStream(“/db.properties”);

Properties ps=new Properties();

ps.load(is);

mysqlDriver=ps.getProperty(“mysqlDriver”);

url=ps.getProperty(“url”);

user=ps.getProperty(“user”);

password=ps.getProperty(“password”);

Class.forName(mysqlDriver);

} catch (Exception e) {

e.printStackTrace();

}

}

//获取数据库连接

public static Connection getConn(){

Connection conn=null;

try {

conn= DriverManager.getConnection(url, user, password);

} catch (Exception e) {

e.printStackTrace();

System.out.println(“获取数据库链接异常”);

}

return conn;

}

//关闭资源

public static void close(Object…objs){

if(objs!=null&&objs.length>0){

for(int i=0;i

try {

if(objs[i] instanceof Connection){

((Connection)objs[i]).close();

}else if(objs[i] instanceof PreparedStatement){

((PreparedStatement)objs[i]).close();

}else if(objs[i] instanceof ResultSet){

((ResultSet)objs[i]).close();

}

} catch (Exception e) {

e.printStackTrace();

System.out.println(“关闭资源 异常”);

}

}

}

}

}

———————

作者:mischen520

来源:CSDN

原文:https://blog.csdn.net/miachen520/article/details/52005505

版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
所有业务逻辑类皆可调用该类 package com.parddu.dao; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * 通用DAO类 * @author parddu * @version Sep 29, 2010 10:16:23 AM */ public class CommonDAO { /** * 修改数据 * @param sql sql语句 * @param param 参数列表 * @return 修改记录行数 */ public int update(String sql,List param){ int row = -1; Connection conn = null; PreparedStatement update = null; try { conn = DButil.getConn(); update = conn.prepareStatement(sql); this.setParam(update, param); row = update.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally{ DButil.closeConn(update, conn); } return row; } /** * 查询数据 * @param sql sql语句 * @param param 参数 * @return 结果集HashMap<列名,值对象> */ public List<HashMap> query(String sql,List param) { List<HashMap> list = new ArrayList<HashMap>(); Connection conn = null; PreparedStatement query = null; ResultSet rs = null; try { conn = DButil.getConn(); query = conn.prepareStatement(sql); this.setParam(query, param); rs = query.executeQuery(); if(rs!=null){ //取得所有的列名 ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String[] columnNameArray = new String[columnCount]; for(int i=0;i<columnCount;i++){ columnNameArray[i] = rsmd.getColumnName(i+1); } //读取结果 while(rs.next()){ HashMap<String,Object> hm = new HashMap<String,Object>(); for(String cn : columnNameArray){ hm.put(cn, rs.getObject(cn)); } list.add(hm); } } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally{ DButil.closeConn(rs,query, conn); } return list; } /** * 查询数据 * @param sql sql语句 * @param param 参数 * @return 结果集List<实体对象> */ public List query(String sql,List param,Class cla){ List list = new ArrayList(); Connection conn = null; PreparedStatement query = null; ResultSet rs = null; try { conn = DButil.getConn(); query = conn.prepareStatement(sql); this.setParam(query, param); rs = query.executeQuery(); if(rs!=null){ //取得所有的列名 ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String[] columnNameArray = new String[columnCount]; for(int i=0;i<columnCount;i++){ columnNameArray[i] = rsmd.getColumnName(i+1); } //得到所有列和方法匹配的项 List<PropertyMthod> mList = new ArrayList<PropertyMthod>(); for(String columnName : columnNameArray){ Method m = this.getMethod(cla,columnName); if(m!=null){ PropertyMthod pm = new PropertyMthod(m,columnName); mList.add(pm); } } //读取结果 while(rs.next()){ Object o = cla.newInstance(); for(PropertyMthod pm : mList){ this.invokeSetMethod(o, pm.getMethod(), rs, pm.getColumn()); } list.add(o); } } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally{ DButil.closeConn(rs,query, conn); } return list; } /** * 调用目标对象的set方法 * @param o 目标对象 * @param m set方法 * @param rs 结果集 * @param columnName 列名 * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ private void invokeSetMethod(Object o,Method m,ResultSet rs,String columnName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{ String paramType = m.getParameterTypes()[0].getName(); paramType = paramType.substring(paramType.lastIndexOf(".")+1); /*****特殊类型处理******/ if("Integer".equals(paramType)){ paramType = "Int"; } String strName = "get" + this.firstUpper(paramType); Method rsMethod = rs.getClass().getDeclaredMethod(strName, String.class); m.invoke(o, rsMethod.invoke(rs, columnName)); } /** * 匹配指定列名的set方法 * @param o * @param column * @return * @throws NoSuchMethodException * @throws SecurityException */ private Method getMethod(Class o,String column) throws SecurityException, NoSuchMethodException{ Method m = null; List<String> strList = new ArrayList<String>(); /********set方法转换设置***********/ strList.add(column); //去掉下划线stu_name--->stuName strList.add(this.delLine(column,"_")); boolean flage = false; Method[] mlist = o.getDeclaredMethods(); for(Method tempm : mlist){ for(String s:strList){ String name = "set"+this.firstUpper(s); if(tempm.getName().equals(name)){ m=tempm; flage = true; break; } } if(flage){ break; } } if(!flage){ System.out.println("查询列名" + column + "在实体中无方法名匹配,值将不会被设置!"); } return m; } /** * 删除列分割符 * @return */ private String delLine(String str,String fg){ String result = str; if(str.indexOf(fg)!=-1){ result = str.substring(0,str.indexOf(fg))+ this.firstUpper(str.substring(str.indexOf(fg)+1)); result = delLine(result,fg); } return result; } /** * 将给定字符串首字母修改为小写 * @param str 字符串 * @return 转换后的字符串 */ private String firstUpper(String str){ return (str.charAt(0)+"").toUpperCase()+str.substring(1); } /** * 设置参数 * @param ps 预编译对象 * @param param 参数集合 * @throws SQLException */ private void setParam(PreparedStatement ps,List param) throws SQLException{ if(param!=null&&param;.size()>0){ for(int i=0;i<param.size();i++){ ps.setObject(i+1, param.get(i)); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值