package com.kxrjkf.user.daoex.impl;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import com.kxrjkf.user.daoex.BaseDAO;
import com.kxrjkf.user.domain.Column;
import com.kxrjkf.user.domain.ID;
import com.kxrjkf.user.domain.Table;
import com.kxrjkf.user.util.DBUtil;
public
class BaseDAOImplEXS
<T
>
implements BaseDAO
<T
> {
private
Class clazz
= (
Class) ((ParameterizedType)(
this.getClass().getGenericSuperclass())).getActualTypeArguments()[0];
private QueryRunner qr
=
new QueryRunner();
public
void add(T bean)
throws SQLException {
//1、构造SQL添加记录语句
//获取表名
Table table
= (Table) clazz.getAnnotation(Table.
class);
String tableName
= table.value();
String sql
=
"insert into "
+ tableName
+
" values(";
int sum
= clazz.getDeclaredFields().length;
for (
int i
= sum; i
> 0; i
--) {
sql
+=
"?";
if (i
!=1) {
sql
+=
",";
}
}
sql
+=
")";
//insert into user values(?,?,?)
//2、将实际参数按顺序存入Object数组
//获取主键名和列名
Field[] fields
= clazz.getDeclaredFields();
int zong
=fields.length;
//用于记录总列数
String zhujian
= null;
//用于存放主键名
String[] lie
=
new
String[zong];
//存放列名
for (
int i
= 0; i
< lie.length; i
++) {
try {
ID id
= fields[i].getAnnotation(ID.
class);
//获取主键名注解
zhujian
= id.value();
//得到主键名
continue;
//如果有主键注解的话,肯定不是普通列,就跳过本次循环
}
catch (
NullPointerException e) {
//出现这个异常表示当前循环的属性上面没有主键注解
}
try {
Column column
= fields[i].getAnnotation(Column.
class);
//获取列名注解
lie[i]
= column.value();
}
catch (
NullPointerException e) {
//出现这个异常表示当前循环的属性上面没有列名注解
}
}
System.out.println(zong);
Object[] objects
=null;
try {
objects
=
new
Object[zong];
for (
int i
= 0; i
< zong; i
++) {
fields[i].setAccessible(true);
objects[i]
= fields[i].get(bean);
/* System.out.println(fields[i].getName()+":"+objects[i]);
* 此处输出结果:
id:3
username:zhangsan
password:123456*/
}
}
catch (
Exception e) {
e.printStackTrace();
}
for (
Object object : objects) {
System.out.println(object);
}
//3、执行sql语句
qr.update(DBUtil.getConnection(), sql, objects);
}
}