根据ResultSetMetaData对象动态创建pojo或其集合(JDBC)
数据库脚本:
Code
CREATE DATABASE /*!32312 IF NOT EXISTS*/`jsptest` /*!40100 DEFAULT CHARACTER SET gbk */;
USE `jsptest`;
/*Table structure for table `t_user` */
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) default NULL,
`userpwd` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gbk;
/*Data for the table `t_user` */
insert into `t_user`(`id`,`username`,`userpwd`) values (4,'jerry','aa'),(5,'kay','aa'),(6,'tom','123');
CREATE DATABASE /*!32312 IF NOT EXISTS*/`jsptest` /*!40100 DEFAULT CHARACTER SET gbk */;
USE `jsptest`;
/*Table structure for table `t_user` */
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) default NULL,
`userpwd` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gbk;
/*Data for the table `t_user` */
insert into `t_user`(`id`,`username`,`userpwd`) values (4,'jerry','aa'),(5,'kay','aa'),(6,'tom','123');
由于没有映射文件,所以要求pojo中的属性必须和数据表中的列名相同:
Code
package com.kay.entity;
/**
* User 实体类
* @author 樊凯
*
*/
public class User {
private int id;
private String username;
private String userpwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
}
package com.kay.entity;
/**
* User 实体类
* @author 樊凯
*
*/
public class User {
private int id;
private String username;
private String userpwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
}
获得唯一的pojo方法:
Code
/**
* 获得唯一对象
* @param clazz pojo的class
* @param sql select sql语句(可带占位符参数)
* @param pars 参数对应的值数组
* @return
*/
public static Object get(Class clazz,String sql,Object[] pars)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object obj = null;
//获得数据库连接
conn = getConnection();
try {
//给sql的参数赋值并执行查询
ps = conn.prepareStatement(sql);
for (int i = 0; i < pars.length; i++) {
ps.setObject(i+1, pars[i]);
}
rs = ps.executeQuery();
//根据查询结果获得该rs对应的ResultSetMetaData对象
ResultSetMetaData rsmd = rs.getMetaData();
//获得返回的列的数量
int count = rsmd.getColumnCount();
//该数组存放列的名称
String[] columns = new String[count];
//向数组中存放列的名称
for (int i = 0; i < columns.length; i++) {
columns[i] = rsmd.getColumnLabel(i+1);
}
//如果结果中有数据存在
if(rs.next())
{
//根据pojo的class反射获得其对象
obj = clazz.newInstance();
//获得pojo所有的方法
Method[] methods = obj.getClass().getMethods();
for (int i = 0; i < columns.length; i++) {
//根据列名获得set方法<由于没有映射文件,要求pojo中的属性必须和列名相同>
String column = columns[i];
String methodName = "set" + column.substring(0,1).toUpperCase() + column.substring(1);
//根据获得的方法数组去迭代 如果方法名称和上面获得的set方法相同 就执行这个方法
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if(method.getName().equals(methodName))
{
method.invoke(obj, rs.getObject(column));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
close(rs,ps,conn);
}
return obj;
}
/**
* 获得唯一对象
* @param clazz pojo的class
* @param sql select sql语句(可带占位符参数)
* @param pars 参数对应的值数组
* @return
*/
public static Object get(Class clazz,String sql,Object[] pars)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object obj = null;
//获得数据库连接
conn = getConnection();
try {
//给sql的参数赋值并执行查询
ps = conn.prepareStatement(sql);
for (int i = 0; i < pars.length; i++) {
ps.setObject(i+1, pars[i]);
}
rs = ps.executeQuery();
//根据查询结果获得该rs对应的ResultSetMetaData对象
ResultSetMetaData rsmd = rs.getMetaData();
//获得返回的列的数量
int count = rsmd.getColumnCount();
//该数组存放列的名称
String[] columns = new String[count];
//向数组中存放列的名称
for (int i = 0; i < columns.length; i++) {
columns[i] = rsmd.getColumnLabel(i+1);
}
//如果结果中有数据存在
if(rs.next())
{
//根据pojo的class反射获得其对象
obj = clazz.newInstance();
//获得pojo所有的方法
Method[] methods = obj.getClass().getMethods();
for (int i = 0; i < columns.length; i++) {
//根据列名获得set方法<由于没有映射文件,要求pojo中的属性必须和列名相同>
String column = columns[i];
String methodName = "set" + column.substring(0,1).toUpperCase() + column.substring(1);
//根据获得的方法数组去迭代 如果方法名称和上面获得的set方法相同 就执行这个方法
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if(method.getName().equals(methodName))
{
method.invoke(obj, rs.getObject(column));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
close(rs,ps,conn);
}
return obj;
}
获得集合方法:
Code
/**
* 获得一个pojo的List集合
* @param clazz pojo的class
* @param sql select sql语句(可带?占位符)
* @param pars 占位符对应的参数值数组
* @return
*/
public static List find(Class clazz,String sql,Object[] pars)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
conn = getConnection();
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < pars.length; i++) {
ps.setObject(i+1, pars[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] columns = new String[count];
for (int i = 0; i < columns.length; i++) {
columns[i] = rsmd.getColumnLabel(i+1);
}
while(rs.next())
{
//根据反射构建新的对象
Object obj = clazz.newInstance();
Method[] methods = obj.getClass().getMethods();
for (int i = 0; i < columns.length; i++) {
String column = columns[i];
String methodName = "set" + column.substring(0,1).toUpperCase() + column.substring(1);
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if(method.getName().equals(methodName))
{
method.invoke(obj, rs.getObject(column));
}
}
}
//将该对象放入集合
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
close(rs,ps,conn);
}
return list;
}
/**
* 获得一个pojo的List集合
* @param clazz pojo的class
* @param sql select sql语句(可带?占位符)
* @param pars 占位符对应的参数值数组
* @return
*/
public static List find(Class clazz,String sql,Object[] pars)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
conn = getConnection();
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < pars.length; i++) {
ps.setObject(i+1, pars[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] columns = new String[count];
for (int i = 0; i < columns.length; i++) {
columns[i] = rsmd.getColumnLabel(i+1);
}
while(rs.next())
{
//根据反射构建新的对象
Object obj = clazz.newInstance();
Method[] methods = obj.getClass().getMethods();
for (int i = 0; i < columns.length; i++) {
String column = columns[i];
String methodName = "set" + column.substring(0,1).toUpperCase() + column.substring(1);
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if(method.getName().equals(methodName))
{
method.invoke(obj, rs.getObject(column));
}
}
}
//将该对象放入集合
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
close(rs,ps,conn);
}
return list;
}
测试:
Code
public static void main(String[] args) throws Exception{
DBUtil db = new DBUtil();
String sql2 = "select * from t_user where id = ?";
User user = (User) db.get(User.class, sql2, new Object[]{4});
System.out.println(user.getId() + " : " + user.getUsername() + " : " + user.getUserpwd()) ;
String sql = "select * from t_user";
List list = db.find(User.class, sql, new Object[]{});
for (int i = 0; i < list.size(); i++) {
User user2 = (User) list.get(i);
System.out.println(user2.getId() + " : " + user2.getUsername() + " : " + user2.getUserpwd()) ;
}
}
public static void main(String[] args) throws Exception{
DBUtil db = new DBUtil();
String sql2 = "select * from t_user where id = ?";
User user = (User) db.get(User.class, sql2, new Object[]{4});
System.out.println(user.getId() + " : " + user.getUsername() + " : " + user.getUserpwd()) ;
String sql = "select * from t_user";
List list = db.find(User.class, sql, new Object[]{});
for (int i = 0; i < list.size(); i++) {
User user2 = (User) list.get(i);
System.out.println(user2.getId() + " : " + user2.getUsername() + " : " + user2.getUserpwd()) ;
}
}