使用BeanUtils工具类操作JavaBean

一、字段与属性
    1、Java类的属性
        Java类的属性,它和之前的类中的成员变量不一样,在之前的文章中,有时我也将属性称之为别名,Java类的属性是通过类中的getter()与setter()方法来确定的,例如  getXxx() ,在这个getter方法中,去除方法名前面的"get"后,剩下的字母的第一个字母小写即为Java类的属性
    2、字段
        字段就是之前我们常说的类的属性,也就是类中的成员变量, 一般情况下,字段名和属性名是一样的
二、BeanUtils工具包
    该工具包是apache的一个用来操作Java类属性的工具包,意味着我们能够直接使用该工具包中的方法,来完成对Java类属性的操作,如之前查询数据库中的数据时,我们将查到的ResultSet结果集利用getMetaData()方法得到ResultSetMetaData对象,并利用该对象和Map集合,运用反射,将查取到的数据赋值给了Java类属性,而有了BeanUtils工具包后,我们可以调用该工具包中的setProperty()方法与getProperty()来完成对Java类属性的赋值与获取对应值,下面来说说BeanUtils的导入步骤
     ①去apache官网下载commons-beanutils-1.9.3.jar与commons-logging-1.2.jar包
                             http://commons.apache.org/proper/commons-logging/download_logging.cgi
     ②将其放在本地项目的一个文件夹中,然后右键单击jar文件,选择bulid  path,然后add to bulidpath
完成以上步骤,就可以使用BeanUtils工具类了,下面是使用其中的的setProperty()方法一个具体实例
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.beanutils.BeanUtils;
public class DAO {

    public void updata(String sql,Object ... args){//数据库的更新操作,可实现增、删、改的操作
       Connection con = null;
       PreparedStatement ps = null;
       
       try {
                    con = getConnection();//获取数据库连接
                    ps = con.prepareStatement(sql);
                    for(int i = 0;i<args.length;i++){//填充占位符
                           ps.setObject(i + 1, args[i]);
                    }
                    ps.executeUpdate();
             } catch (Exception e) {
                    e.printStackTrace();
             }finally{
                    JDBCTools.release(con, ps);//释放数据库连接
             }
    }
    public <T> T get(Class<T> clazz,String sql,Object ... args){//数据库的查询操作
       T entity = null;
       Connection con = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       
       try {
                    con = getConnection();
                    ps = con.prepareStatement(sql);
                    for(int i = 0;i < args.length;i++){//填充占位符
                           ps.setObject(i + 1,args[i]);
                    }
                    rs = ps.executeQuery();//得到结果集,利用它可以知道某一行中某一列的具体值
                    if(rs.next()){
                           ResultSetMetaData rsmd = rs.getMetaData();//该对象可以知道结果集有几列,以及每一列所对应的别名等信息
                           Map<String,Object> valueMap = new HashMap<>();//建立Map集合用来存结果集中的列名以及对应的属性值
                           for(int i = 0;i < rsmd.getColumnCount();i++){
                                 String ColumnLabel = rsmd.getColumnLabel(i + 1);//得到查询出的每一列的列名
                                 Object ColumnValue = rs.getObject(i + 1);//得到每一列所对应的值
                                 valueMap.put(ColumnLabel, ColumnValue);
                           }
                if(valueMap.size() > 0){
                    entity = clazz.newInstance();
                           for(Map.Entry<String, Object> entry : valueMap.entrySet()){//利用反射为对应的属性赋值
                               String fieldName = entry.getKey();
                               Object fieldvalue = entry.getValue();
//                             Field f1 = clazz.getDeclaredField(fieldName);//利用反射赋值,不推荐使用
//                             f1.setAccessible(true);
//                             f1.set(entity, fieldvalue);
                               BeanUtils.setProperty(entity, fieldName, fieldvalue);//对Java类属性赋值
                           }
                }
                    }
             } catch (Exception e) {
            e.printStackTrace();
             }
       
       return entity;
    }
       public Connection getConnection() throws Exception{//连接数据库
             String driverClass = null;
             String url = null;
             String user = null;
             String password = null;
             
             Properties properties = new Properties();
             
             InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
             properties.load(in);
             
             driverClass = properties.getProperty("driver");
             url = properties.getProperty("jdbcurl");
             user = properties.getProperty("user");
             password = properties.getProperty("password");
             Class.forName(driverClass);
             return DriverManager.getConnection(url, user, password);
       }
       public void release(Connection con , Statement state){//关闭数据库连接
             if(state != null){
                    try {
                           state.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
             }
             if(con != null){
                    try {
                           con.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
             }
             
       }
       public void release(ResultSet rs , Connection con , Statement state){//关闭数据库连接
             if(rs != null)
             {
                    try {
                           rs.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
             }
             if(state != null){
                    try {
                           state.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
             }
             if(con != null){
                    try {
                           con.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
             }
       }
}
现在本地数据库中有一个表,如下:
现在要对该表进行查询操作,并且针对该表定义了一个Student类( 可以看到Student类中的成员变量名与sql语句中的Java类属性名是一样的),用于以测试上面的实例,具体代码如下:
import org.junit.Test;

public class TestDAO {

	DAO dao = new DAO();
	@Test
	public void testGet() {
        String sql = "SELECT Flow_ID flowID,type,ID_Card iDcard FROM examstudent WHERE Flow_ID=?";
        System.out.println(dao.get(Student.class, sql, 10002));
	}
class Student {
	public int flowID;//流水号
	public String type;//考试类型
	public String iDcard;//身份证号
	public String examcard;//准考证号码
	public String studentName;//学生姓名
	public String location;//区域
	public int grade;//成绩
	
	public int getFlowID() {
		return flowID;
	}


	public void setFlowID(int flowID) {
		this.flowID = flowID;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}


	public String getiDcard() {
		return iDcard;
	}


	public void setiDcard(String iDcard) {
		this.iDcard = iDcard;
	}


	public String getExamcard() {
		return examcard;
	}


	public void setExamcard(String examcard) {
		this.examcard = examcard;
	}


	public String getStudentName() {
		return studentName;
	}


	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}


	public String getLocation() {
		return location;
	}


	public void setLocation(String location) {
		this.location = location;
	}


	public int getGrade() {
		return grade;
	}


	public void setGrade(int grade) {
		this.grade = grade;
	}


	public Student() {
		super();
	}
	public Student(int flowID, String type, String iDcard, String examcard, String studentName, String location,
			int grade) {
		super();
		this.flowID = flowID;
		this.type = type;
		this.iDcard = iDcard;
		this.examcard = examcard;
		this.studentName = studentName;
		this.location = location;
		this.grade = grade;
	}


	@Override
	public String toString() {
		return "Student [flowID=" + flowID + ", type=" + type + ", iDcard=" + iDcard + ", examcard=" + examcard
				+ ", studentName=" + studentName + ", location=" + location + ", Grade=" + grade + "]";
	}




}
}
最后的运行结果为:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值