• java反射机制编写简单万能DAO类


    由于在搭建编写万能DAO时,已经写了大量的代码

    在此只给出部分的测试源码

    如有需要完整项目或者有任何建议联系973639421

    package com.oman.bean;
    
    public class Person {
    	private int id;
    	private String name;
    	private int age;
    	private int type;
    	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 int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	public int getType() {
    		return type;
    	}
    	public void setType(int type) {
    		this.type = type;
    	}
    	
    	
    }
    

    package com.oman.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    import com.oman.bean.Person;
    import com.oman.util.BaseConnection;
    
    public class PersonDao {
    	
    	//编写普通查询方法
    	public ArrayList<Person> getList(){
    		ArrayList<Person> list = new ArrayList<Person>();
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		String sql = "select * from Person";
    		try {
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    			while(rs.next()){
    				Person person = new Person();
    				person.setId(rs.getInt("id"));
    				person.setName(rs.getString("name"));
    				person.setAge(rs.getInt("age"));
    				person.setType(rs.getInt("type"));
    				list.add(person);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps, rs);
    		}
    		return list;
    	}
    	
    	//编写普通插入方法
    	public boolean insert(Person person){
    
    		boolean flag = false;
    		
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		
    		String sql = "insert into Person(name,age,type) values(?,?,?)";
    		try {
    			ps = conn.prepareStatement(sql);
    			ps.setString(1, person.getName());
    			ps.setInt(2, person.getAge());
    			ps.setInt(3, person.getType());
    			int a = ps.executeUpdate();
    			if(a > 0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag;
    		
    	}
    	
    	//编写普通修改方法
    	public boolean update(Person person){
    		boolean flag = false;
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		String sql = "update person set name = ?,age = ?,type = ? where id = ?";
    		try {
    			ps = conn.prepareStatement(sql);
    			ps.setString(1, person.getName());
    			ps.setInt(2, person.getAge());
    			ps.setInt(3, person.getType());
    			ps.setInt(4, person.getId());
    			int a = ps.executeUpdate();
    			if(a>0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag;
    	}
    	
    	
    }

    package com.oman.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    public class BaseConnection {
    	
    	//首先编写一个获取Connection的方法
    	public static Connection getConnection (){
    		Connection conn = null;
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
    			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","root");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return conn;
    	}
    	
    	//其次编写关闭资源的方法
    	public static void closeRec(Connection conn,PreparedStatement ps){
    		try {
    			if(ps!=null){
    				ps.close();
    			}
    			if(conn!=null){
    				conn.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static void closeRec(Connection conn,PreparedStatement ps,ResultSet rs){
    		try {
    			if(ps!=null){
    				ps.close();
    			}
    			if(conn!=null){
    				conn.close();
    			}
    			if(rs!=null){
    				rs.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    }
    

    package com.oman.util;
    
    import java.lang.reflect.Field;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    
    import com.oman.bean.Person;
    
    //编写万能DAO类
    public class BaseDao {
    
    	//查询所有
    	public ArrayList getList(Class cl){
    		ArrayList list = new ArrayList();
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		//由于数据库中的表名对应的是实体类的类名,所以可以通过传入的类得到表名cl.getSimpleName()
    		String sql = "select * from " + cl.getSimpleName();
    		//获取类对象的所有属性
    		Field[] fi = cl.getDeclaredFields();
    		try {
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    			while(rs.next()){
    				Object object = cl.newInstance();//实例化类对象
    				for(Field ff:fi){
    					ff.setAccessible(true);//打开控制访问权限
    					ff.set(object, rs.getObject(ff.getName()));
    				}
    				list.add(object);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps, rs);
    		}
    		return list;
    	}
    
    	//根据表的主键查询表的对象
    	public Object getObjectById(Class cl,int id){
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		Field[] fi = cl.getDeclaredFields();
    		//由于类中不一定用id表示编号,但是通常类中的第一个属性为编号id
    		String sql = "select * from " + cl.getSimpleName() + " where " + fi[0].getName() + " = " + id;
    		Object object = null;
    		try {
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    			while(rs.next()){
    				object = cl.newInstance();
    				for(Field ff:fi){
    					ff.setAccessible(true);
    					ff.set(object, rs.getObject(ff.getName()));
    				}
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps, rs);
    		}
    		return object;
    	}
    	
    	//根据特定条件查询
    	public ArrayList getListByCondition(Class cl,String name,Object value){
    		ArrayList list = new ArrayList();
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		
    		String sql = "select * from " + cl.getSimpleName() + " where " + name + " = '" + value+"'";
    		Field[] fi = cl.getDeclaredFields();
    		try {
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    			while(rs.next()){
    				Object object = cl.newInstance();//实例化类对象
    				for(Field ff:fi){
    					ff.setAccessible(true);//打开控制访问权限
    					ff.set(object, rs.getObject(ff.getName()));
    				}
    				list.add(object);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps, rs);
    		}
    		return list;
    	}
     	
    	//插入对象
    	public boolean insert(Object object){
    		boolean flag = false;
    
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		//获取对象的类
    		Class cl = object.getClass();
    		Field[] fi = cl.getDeclaredFields();
    				//insert into Person(name) values(?,?,?)
    				//以下开始拼接sql语句
    				//两个String对象的连接是很耗费资源的,以下方法可以通过StringBuffer优化,
    				//可以减少资源利用,使用apand对StringBuffer进行拼接
    		String sql = "insert into " + cl.getSimpleName() + " (";
    		for (int i = 1; i < fi.length; i++) {
    			sql = sql + fi[i].getName();
    			if (i < fi.length-1) {
    				sql = sql + ",";
    			}
    		}
    		sql = sql + ") values(";
    		for (int i = 1; i < fi.length; i++) {
    			sql = sql + "?";
    			if (i < fi.length-1) {
    				sql = sql + ",";
    			}
    		}
    		sql = sql + ")";
    		
    		try {
    			ps = conn.prepareStatement(sql);
    			for(int i = 1;i<fi.length;i++){
    				fi[i].setAccessible(true);
    				ps.setObject(i, fi[i].get(object));
    			}
    			int a = ps.executeUpdate();
    			if(a > 0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag;
    
    	}
    
    	//优化插入
    	public boolean insert1(Object object){
    		boolean flag = false;
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		Class cl = object.getClass();
    		Field[] fi = cl.getDeclaredFields();
    		StringBuffer sb = new StringBuffer();
    		sb.append("insert into ");
    		sb.append(cl.getSimpleName());
    		sb.append(" (");
    		for(int i = 1;i<fi.length;i++){
    			sb.append(fi[i].getName());
    			if(i!=fi.length-1){
    				sb.append(" , ");
    			}
    		}
    		sb.append(") values (");
    		for(int i = 1;i<fi.length;i++){
    			sb.append(" ? ");
    			if(i!=fi.length-1){
    				sb.append(" , ");
    			}
    		}
    		sb.append(" ) ");
    		try {
    			ps = conn.prepareStatement(sb.toString());
    			for(int i = 1;i<fi.length;i++){
    				fi[i].setAccessible(true);
    				ps.setObject(i, fi[i].get(object));
    			}
    			int a = ps.executeUpdate();
    			if(a>0){
    				flag = true;
    			}
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag;
    	}
    	
    	//更新
    	public boolean update(Object object){
    		boolean flag = false;
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		Class cl = object.getClass();
    		Field[] fi = cl.getDeclaredFields();
    		StringBuffer sb = new StringBuffer();
    			//update person set name = ?,age = ?,type = ? where id = ?
    		sb.append(" update ");
    		sb.append(cl.getSimpleName());
    		sb.append(" set ");
    		for(int i = 1;i<fi.length;i++){
    			fi[i].setAccessible(true);
    			sb.append(fi[i].getName());
    			sb.append(" = ? ");
    			if(i!=fi.length-1){
    				sb.append(" , ");
    			}
    		}
    		sb.append(" where ");
    		sb.append(fi[0].getName());
    		sb.append("=?");
    		
    		try {
    			ps = conn.prepareStatement(sb.toString());
    			for(int i = 1;i<fi.length;i++){
    				fi[i].setAccessible(true);
    				ps.setObject(i, fi[i].get(object));
    			}
    			fi[0].setAccessible(true);
    			ps.setObject(fi.length, fi[0].get(object));
    			int a = ps.executeUpdate();
    			if(a>0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag;
    	}
    	
    	//根据id删除
    	public boolean delete(Class cl , int id){
    		boolean flag = false;
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		Field[] fi = cl.getDeclaredFields();
    		String sql = "delete from "+cl.getSimpleName()+" where "+fi[0].getName()+" = ?";
    		try {
    			ps = conn.prepareStatement(sql);
    			ps.setObject(1, id);
    			int a = ps.executeUpdate();
    			if(a>0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag ;
    	
    	}
    	
    	//根据特定条件删除
    	public boolean deleteByCondition(Class cl , String name,Object value){
    		boolean flag = false;
    		Connection conn = BaseConnection.getConnection();
    		PreparedStatement ps = null;
    		Field[] fi = cl.getDeclaredFields();
    		String sql = "delete from "+cl.getSimpleName()+" where "+name+" = ?";
    		try {
    			ps = conn.prepareStatement(sql);
    			ps.setObject(1, value);
    			int a = ps.executeUpdate();
    			if(a>0){
    				flag = true;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			BaseConnection.closeRec(conn, ps);
    		}
    		return flag ;
    	
    	}
    
    	
    	public static void main(String[] args) {
    		
    		//测试getList()
    		BaseDao baseDao = new BaseDao();
    //		ArrayList<Person> plist = baseDao.getList(Person.class);
    //		for(Person p:plist){
    //			System.out.println("编号:"+p.getId()+" 姓名:"+p.getName()+" 年龄:"+p.getAge());
    //		}
    			/*测试效果
    				编号:1 姓名:小明 年龄:21
    				编号:2 姓名:小华 年龄:22
    				编号:3 姓名:李四 年龄:34
    			*/
    		
    		//测试getObjectById()
    //		Person person = (Person) baseDao.getObjectById(Person.class, 1);
    //		System.out.println("编号:"+person.getId()+" 姓名:"+person.getName());
    			/*测试效果
    				编号:1 姓名:小明
    			 */
    		
    		//测试getListByCondition()
    //		ArrayList<Person> plist = baseDao.getListByCondition(Person.class,"name","李四");
    //		for(Person p:plist){
    //			System.out.println("编号:"+p.getId()+" 姓名:"+p.getName()+" 年龄:"+p.getAge());
    //		}
    			/*测试效果
    			  	编号:3 姓名:李四 年龄:34
    			 */
    		
    		//测试insert()
    //		Person person = new Person();
    //		person.setName("王五");
    //		person.setAge(44);
    //		person.setType(2);
    //		boolean flag = baseDao.insert(person);
    //		if(flag == true){
    //			System.out.println("插入成功");
    //		}
    			/*测试效果
    			  	插入成功
    			 */
    		
    		//测试update()
    //		Person person = new Person();
    //		person.setName("王五五");
    //		person.setAge(444);
    //		person.setType(2);
    //		person.setId(4);
    //		boolean flag = baseDao.update(person);
    //		if(flag == true){
    //			System.out.println("修改成功");
    //		}
    			/*测试效果
    	  			修改成功
    			 */
    		
    		//测试delete()与deleteBySome()
    		boolean flag = baseDao.deleteByCondition(Person.class, "name","王五五");
    		if(flag == true){
    			System.out.println("删除成功");
    		}
    			/*测试效果
    				删除成功
    			 */
    		//baseDao.delete(Person.class, 3);
    	}
    }
    

    package com.oman.main;
    
    import java.util.ArrayList;
    
    import com.oman.bean.Person;
    import com.oman.bean.Person_type;
    import com.oman.dao.PersonDao;
    import com.oman.dao.Person_typeDao;
    
    public class TestMain {
    	public static void main(String[] args) {
    		
    		PersonDao personDao = new PersonDao();
    		ArrayList<Person> plist = personDao.getList();
    		for(Person person : plist){
    			System.out.println(person.getName());
    		}
    		
    		System.out.println("------");
    		
    		Person_typeDao person_typeDao = new Person_typeDao();
    		ArrayList<Person_type> ptlist = person_typeDao.getList();
    		for(Person_type person_type : ptlist){
    			System.out.println(person_type.getName());
    		}
    		
    		
    	}
    }
    


  • 相关阅读:
    Handle( )
    GetFileOpenName()、GetFilesavename
    笔记linux一些常用命令
    Git的简单使用
    express+mongodb+mongoose简单入门
    浅谈node Async异步处理模块
    parse,tryparse区别
    .NET一般处理程序如何获取AJAX传递的参数
    UOJ461 新年的Dog划分【图论,交互】
    UOJ243【UR #16】破坏导蛋【计算几何,分块】
  • 原文地址:https://www.cnblogs.com/laohuihui/p/5308748.html
Copyright © 2020-2023  润新知