反射在一定程度上破坏了封装性,需要合理使用
Dept类 Emp类 DBUtilTest工具类
三个类的代码在文章最下方
要查询N张表的数据,但是不想写N多的方法,能否写一个方法完成所有表的查询工作
public class BaseDaoImpl {
/**
* 统一的查询表的方法
* @param sql 不同的sql语句
* @param params sql语句的参数
* @param clazz sql语句查询返回的对象
* @return
*/
public List getRows(String sql,Object[] params,Class clazz){
List list = new ArrayList();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
//建立连接
connection = DBUtil.getConnection();
//创建pstmt对象
pstmt = connection.prepareStatement(sql);
//给sql语句填充参数
if(params!=null){
for(int i = 0;i<params.length;i++){
pstmt.setObject(i+1,params[i]);
}
}
//开始执行查询操作,resultset中有返回的结果,需要讲返回的结果放置到不同的对象中
resultSet = pstmt.executeQuery();
//获取结果集合的元数据对象
ResultSetMetaData metaData = resultSet.getMetaData();
//判断查询到的每一行记录中包含多少个列
int columnCount = metaData.getColumnCount();
//循环遍历resultset
while(resultSet.next()){
//创建放置具体结果属性的对象
Object obj = clazz.newInstance();
for(int i= 0;i<columnCount;i++){
//从结果集合中获取单一列的值
Object objValue = resultSet.getObject(i+1);
//获取列的名称
String columnName = metaData.getColumnName(i+1).toLowerCase();
//获取类中的属性
//Field address = clazz.getDeclaredField("address");
Field declaredField = clazz.getDeclaredField(columnName);
//获取类中属性对应的set方法
//Method add = clazz.getDeclaredMethod("add", int.class, int.class);
Method method = clazz.getMethod(getSetName(columnName),declaredField.getType());
if(objValue instanceof Number){
//对象是否是特定类的一个实例
//Number类是java.lang包下的一个抽象类,提供了将包装类型拆箱成基本类型的方法
//其包括byte、int、short、long、double、float、boolean、char;
Number number = (Number) objValue;
//System.out.println(address.getName());
String fname = declaredField.getType().getName();
if("int".equals(fname)||"java.lang.Integer".equals(fname)){
//add.invoke(o1,123,123);
method.invoke(obj,number.intValue());
}else if("byte".equals(fname)||"java.lang.Byte".equals(fname)){
method.invoke(obj,number.byteValue());
}else if("short".equals(fname)||"java.lang.Short".equals(fname)){
method.invoke(obj,number.shortValue());
}else if("long".equals(fname)||"java.lang.Long".equals(fname)){
method.invoke(obj,number.longValue());
}else if("float".equals(fname)||"java.lang.Float".equals(fname)){
method.invoke(obj,number.floatValue());
}else if("double".equals(fname)||"java.lang.Double".equals(fname)){
method.invoke(obj,number.doubleValue());
}
}else{
method.invoke(obj,objValue);
}
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeConnection(connection,pstmt,resultSet);
}
return list;
}
public String getSetName(String name){
return "set"+name.substring(0,1).toUpperCase()+name.substring(1);
}
public static void main(String[] args) {
BaseDaoImpl baseDao = new BaseDaoImpl();
// List rows = baseDao.getRows("select empno,ename,sal,deptno from emp where deptno =?", new Object[]{10}, Emp.class);
// for(Iterator it = rows.iterator();it.hasNext();){
// Emp emp = (Emp) it.next();
// System.out.println(emp);
// }
List rows = baseDao.getRows("select deptno,dname,loc from dept", new Object[]{
}, Dept.class);
for(Iterator it = rows.iterator();it.hasNext();){
Dept dept = (Dept) it.next();
System.out.println(dept);
}
}
}
public class Dept {
private int deptno;
private String dname;
private String loc;
public Dept() {
}
public Dept(int deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Dept{" +
"deptno=" + deptno +
", dname='" + dname + '\'' +
", loc='" + loc + '\'' +
'}';
}
}
public class Emp {
private Integer empno;
private String ename;
private String job;
private Integer mrg;
private String hiredate;
private Double sal;
private Double comm;
private Integer deptno;
public Emp(){
}
public Emp(Integer empno, String ename, String job, Integer mrg, String hiredate, Double sal, Double comm, Integer deptno) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mrg = mrg;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMrg() {
return mrg;
}
public void setMrg(Integer mrg) {
this.mrg = mrg;
}
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public Double getComm() {
return comm;
}
public void setComm(Double comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
@Override
public String toString() {
return "Emp{" +
"empno=" + empno +
", ename='" + ename + '\'' +
", job='" + job + '\'' +
", mrg=" + mrg +
", hiredate=" + hiredate +
", sal=" + sal +
", comm=" + comm +
", deptno=" + deptno +
'}';
}
}
public class DBUtilTest {
public static Connection connection ;
public static void testQuery() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp where empno=?";
QueryRunner runner = new QueryRunner();
Emp query = runner.query(connection, sql, new BeanHandler<Emp>(Emp.class), 7369);
System.out.println(query);
connection.close();
}
public static void testList() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp";
QueryRunner runner = new QueryRunner();
List<Emp> query = runner.query(connection, sql, new BeanListHandler<Emp>(Emp.class));
for (Emp emp : query) {
System.out.println(emp);
}
connection.close();
}
public static void testArray() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp";
QueryRunner runner = new QueryRunner();
Object[] object = runner.query(connection, sql, new ArrayHandler());
for (Object o : object) {
System.out.println(o);
}
connection.close();
}
public static void testArrayList() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp";
QueryRunner runner = new QueryRunner();
List<Object[]> query = runner.query(connection, sql, new ArrayListHandler());
for (Object[] objects : query) {
System.out.println(objects[0]+"--"+objects[1]);
}
connection.close();
}
public static void testMap() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp";
QueryRunner runner = new QueryRunner();
Map<String, Object> query = runner.query(connection, sql, new MapHandler());
Set<Map.Entry<String, Object>> entries = query.entrySet();
for (Map.Entry<String, Object> entry : entries) {
System.out.println(entry.getKey()+"---"+entry.getValue());
}
connection.close();
}
public static void testSaclarHandler() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select count(*) from emp";
QueryRunner runner = new QueryRunner();
Object query = runner.query(connection, sql, new ScalarHandler<>());
System.out.println(query);
connection.close();
}
/**
* 自定义handler对象
* @throws SQLException
*/
public static void testMyHandler() throws SQLException {
connection = MySQLDBUtil.getConnection();
String sql ="select * from emp where empno = ?";
QueryRunner runner = new QueryRunner();
Emp emp = runner.query(connection, sql, new ResultSetHandler<Emp>() {
@Override
public Emp handle(ResultSet resultSet) throws SQLException {
if(resultSet.next()){
Emp e = new Emp();
e.setEmpno(resultSet.getInt("empno"));
e.setEname(resultSet.getString("ename"));
return e;
}
return null;
}
},7369);
System.out.println(emp);
connection.close();
}
public static void insert() throws SQLException {
String sql = "insert into emp(empno,ename) values(?,?)";
connection = MySQLDBUtil.getConnection();
QueryRunner queryRunner = new QueryRunner();
queryRunner.update(connection,sql,1234,"msb");
connection.close();
}
public static void update() throws SQLException {
String sql = "update emp set ename=? where empno = ?";
connection = MySQLDBUtil.getConnection();
QueryRunner queryRunner = new QueryRunner();
queryRunner.update(connection,sql,"mashibing",1234);
connection.close();
}
public static void delete() throws SQLException {
String sql = "delete from emp where empno=?";
connection = MySQLDBUtil.getConnection();
QueryRunner queryRunner = new QueryRunner();
queryRunner.update(connection,sql,1234);
connection.close();
}
public static void main(String[] args) throws SQLException {
// testQuery();
// testList();
// testArray();
// testArrayList();
// testMap();
// testSaclarHandler();
// testMyHandler();
// insert();
// update();
delete();
}
}