需求描述
如sql为
select userName,passWord,roleId from users where userId = ?
执行查询动作后得到ResultSet,需要用一个UserBean来接收。
实现
原理还是通过反射,拿到bean中声明的变量,然后执行各种set方法。但注意,命名一点要符合驼峰命名,不然,setuserName()可是不会自动执行的!setUserName();才能执行成功!
查询单个数据,返回一个bean,查询不到就返回null
/**
* 以class声明的变量为准,去rs里找数据
*/
private T changeBean(Class mClass, String columnNames) {
try {
T bean = mClass.getDeclaredConstructor().newInstance();
Field[] beanFields = mClass.getDeclaredFields();
String currentBeanFiledName;
Class> beanType;
for (Field f : beanFields) {
currentBeanFiledName = f.getName();
if (columnNames.contains(currentBeanFiledName)) {
beanType = f.getType();
String setMethodName = "set" + firstUpperCase(currentBeanFiledName);
String beanTypeName = beanType.getSimpleName();
Method m = bean.getClass().getMethod(setMethodName, beanType);
if ("String".equals(beanTypeName)) {
m.invoke(bean, rs.getString(currentBeanFiledName));
} else if ("int".equals(beanTypeName)) {
m.invoke(bean, rs.getInt(currentBeanFiledName));
} else if ("long".equals(beanTypeName)) {
m.invoke(bean, rs.getLong(currentBeanFiledName));
} else if ("float".equals(beanTypeName)) {
m.invoke(bean, rs.getFloat(currentBeanFiledName));
} else if ("double".equals(beanTypeName)) {
m.invoke(bean, rs.getDouble(currentBeanFiledName));
} else {
m.invoke(bean, rs.getObject(currentBeanFiledName));
}
} else {
System.out.println(columnNames + "列明跳过");
}
}
return bean;
} catch (Exception e) {
log.e(e);
return null;
}
}
查询列表数据,就是不断调用changeBean()实现的
List list = new ArrayList();
T bean;
while (rs.next()) {
bean = changeBean(mClass, columnNames);
if (bean != null) {
list.add(bean);
} else {
return null;
}
}
完整代码
这是完整的BaseDao代码,相当于数据库层的基类。
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.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.lkl.web.aaaaa.utils.Log;
public class BaseDao {
public Log log;
public Connection conn;
public PreparedStatement ps;
public ResultSet rs;
public BaseDao(Connection conn, Log log) {
this.conn = conn;
this.log = log;
}
public Connection getConn() {
return conn;
}
/**
* 检查conn是否可用
*
* @throws SQLException
*/
private void checkConn() throws SQLException {
if (conn == null || conn.isClosed()) {
throw new SQLException("connection is not ready");
}
}
public void closeAll() {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
// TODO: handle exception
}
try {
if (ps != null) {
ps.close();
}
} catch (Exception e) {
// TODO: handle exception
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}
public int insert() throws SQLException {
return doModifyAction();
}
public int update() throws SQLException {
return doModifyAction();
}
public int delete() throws SQLException {
return doModifyAction();
}
private int doModifyAction() throws SQLException {
checkConn();
return ps.executeUpdate();
}
public boolean execute() throws SQLException {
checkConn();
return ps.execute();
}
public T query(Class mClass) throws SQLException {
checkConn();
try {
rs = ps.executeQuery();
String columnNames = JSONObject.toJSONString(getColumnNames(rs));
if (rs.next()) {
return changeBean(mClass, columnNames);
} else {
return null;
}
} catch (Exception e) {
log.e(e);
return null;
}
}
public List querys(Class mClass) throws SQLException {
checkConn();
try {
rs = ps.executeQuery();
String columnNames = JSONObject.toJSONString(getColumnNames(rs));
List list = new ArrayList();
T bean;
while (rs.next()) {
bean = changeBean(mClass, columnNames);
if (bean != null) {
list.add(bean);
} else {
return null;
}
}
return list;
} catch (Exception e) {
log.e(e);
return null;
}
}
// 首写字母变大写
private String firstUpperCase(String value) {
return value.substring(0, 1).toUpperCase() + value.substring(1);
}
private String[] getColumnNames(ResultSet rsIn) throws SQLException {
// 取得ResultSet列名
ResultSetMetaData rsmd = rs.getMetaData();
// 获取记录集中的列数
int counts = rsmd.getColumnCount();
// 定义counts个String 变量
String[] columnNames = new String[counts];
// 给每个变量赋值
for (int i = 0; i T changeBean(Class mClass, String columnNames) {
try {
T bean = mClass.getDeclaredConstructor().newInstance();
Field[] beanFields = mClass.getDeclaredFields();
String currentBeanFiledName;
Class> beanType;
for (Field f : beanFields) {
currentBeanFiledName = f.getName();
if (columnNames.contains(currentBeanFiledName)) {
beanType = f.getType();
String setMethodName = "set" + firstUpperCase(currentBeanFiledName);
String beanTypeName = beanType.getSimpleName();
Method m = bean.getClass().getMethod(setMethodName, beanType);
if ("String".equals(beanTypeName)) {
m.invoke(bean, rs.getString(currentBeanFiledName));
} else if ("int".equals(beanTypeName)) {
m.invoke(bean, rs.getInt(currentBeanFiledName));
} else if ("long".equals(beanTypeName)) {
m.invoke(bean, rs.getLong(currentBeanFiledName));
} else if ("float".equals(beanTypeName)) {
m.invoke(bean, rs.getFloat(currentBeanFiledName));
} else if ("double".equals(beanTypeName)) {
m.invoke(bean, rs.getDouble(currentBeanFiledName));
} else {
m.invoke(bean, rs.getObject(currentBeanFiledName));
}
} else {
System.out.println(columnNames + "列名跳过");
}
}
return bean;
} catch (Exception e) {
log.e(e);
return null;
}
}
public void setSql(String sql) throws SQLException {
checkConn();
if (ps != null) {
ps.close();
}
ps = conn.prepareStatement(sql);
System.out.println("sql:" + sql);
}
public String getSqlFields(Class> mClass) {
if (mClass == null) {
return null;
}
Field[] beanFields = mClass.getDeclaredFields();
if (beanFields == null || beanFields.length
使用方法
public class UserDao extends BaseDao {
public UserDao(Connection conn) {
super(conn, Log.newInstance(ConfigATF.DIR_LOG));
}
public int create(String userID, String username, String password, String tel, String bir, String bir2,
String homeID, String sheGongID, int relationship, String bookPage, long createTime) {
try {
setSql("insert into users values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, userID);
ps.setString(2, username);
ps.setString(3, password);
ps.setString(4, tel);
ps.setString(5, bir);
ps.setString(6, bir2);
ps.setString(7, homeID);
ps.setString(8, sheGongID);
ps.setInt(9, relationship);
ps.setString(10, bookPage);
ps.setLong(11, createTime);
ps.setInt(12, 1);
return super.insert();
} catch (Exception e) {
log.e(e);
return -1;
}
}
public int update(String userID, String username, String password, String tel, String bir, String bir2,
String homeID, String sheGongID, int relationship, String bookPage) {
try {
String sql = "update users set username=?,password=?,tel=?,bir=?,bir2=?,homeID=?,sheGongID=?,relationship=?,bookPage=? where userID=?";
setSql(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.setString(3, tel);
ps.setString(4, bir);
ps.setString(5, bir2);
ps.setString(6, homeID);
ps.setString(7, sheGongID);
ps.setInt(8, relationship);
ps.setString(9, bookPage);
ps.setString(10, userID);
return super.update();
} catch (Exception e) {
log.e(e);
return -1;
}
}
public List querys(int pageIndex, int pageSize, String username) {
try {
int start = pageIndex * pageSize;
System.out.println("start:" + start + "," + pageIndex + "," + pageSize);
if (MyUtils.isEmpty(username)) {
String sql = "SELECT data0.userID,data0.username,data0.password,data0.tel,data0.bir,data0.bir2,data0.homeID,data0.sheGongID,data0.relationship,data0.bookPage,data0.createTime,data1.`name` as sheGongName,data2.username as homeName FROM (select userID,username,password,tel,bir,bir2,homeID,sheGongID,relationship,bookPage,createTime from users WHERE `enable`=1 order by createTime DESC limit ?,?)as data0 LEFT JOIN (SELECT shegong.name,shegong.sheGongID FROM shegong ) as data1 on data0.sheGongID = data1.sheGongID LEFT JOIN (SELECT users.username,users.homeID FROM users,home WHERE userID=mainUserID) as data2 on data0.homeID=data2.homeID";
setSql(sql);
ps.setInt(1, start);
ps.setInt(2, pageSize);
} else {
String sql = "SELECT data0.userID,data0.username,data0.password,data0.tel,data0.bir,data0.bir2,data0.homeID,data0.sheGongID,data0.relationship,data0.bookPage,data0.createTime,data1.`name` as sheGongName,data2.username as homeName FROM (select userID,username,password,tel,bir,bir2,homeID,sheGongID,relationship,bookPage,createTime from users WHERE `enable`=1 and username like ? order by createTime DESC limit ?,?)as data0 LEFT JOIN (SELECT shegong.name,shegong.sheGongID FROM shegong ) as data1 on data0.sheGongID = data1.sheGongID LEFT JOIN (SELECT users.username,users.homeID FROM users,home WHERE userID=mainUserID) as data2 on data0.homeID=data2.homeID";
setSql(sql);
ps.setString(1, "%" + username + "%");
ps.setInt(2, start);
ps.setInt(3, pageSize);
}
return super.querys(User.class);
} catch (Exception e) {
log.e(e);
return null;
}
}
public List querys(String str, int maxSize) {
try {
String sql = "select userID,username,password,tel,bir,bir2,homeID,sheGongID,relationship,bookPage,createTime,enable from users "
+ "where userID like ? or username like ? group by userID order by username limit ?";
setSql(sql);
ps.setString(1, "%" + str + "%");
ps.setString(2, "%" + str + "%");
ps.setInt(3, maxSize);
return super.querys(User.class);
} catch (Exception e) {
log.e(e);
return null;
}
}
public int delete(String userID) {
try {
String sql = "delete from users where userID=?";
setSql(sql);
ps.setString(1, userID);
return super.delete();
} catch (Exception e) {
log.e(e);
return -1;
}
}
}