首先Bean在符合JavaBean的要求,即有一个无参的构造方法,所有属性都有一个set和get方法并且set与get方法是set/get+属性名称(属性名称先字母大写)
public class User {
private int id;
private String name;
private Date birthday;
private float money;
public User() {
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ORMTest {
public static void main(String[] args) throws SQLException,
IllegalAccessException, InvocationTargetException, Exception {
User user = (User) getObject(
"select id as Id, name as Name, birthday as Birthday, money as Money from user where id=1",
User.class);
//这里取别名就是为了便列名加set或get就可以是JavaBean中属性的set或get方法
System.out.println(user);
Bean b = (Bean) getObject(
"select id as Id, name as Name, birthday as Birthday, money as Money from user where id=1",
Bean.class);
System.out.println(b);
}
private static String[] getColNames(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for (int i = 1; i <= count; i++) {
colNames[i - 1] = rsmd.getColumnLabel(i);
}
return colNames;
}
static Object getObject(String sql, Class clazz) throws SQLException,
Exception, IllegalAccessException, InvocationTargetException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String[] colNames = getColNames(rs);//得到所有的列名
Object object = null;
Method[] ms = clazz.getMethods();//得到javaBean中所有set或get方法
if (rs.next()) {
object = clazz.newInstance();
for (int i = 0; i < colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;//得到set或get方法名
for (Method m : ms) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));//调用set方法,将该列的值放到set方法当中去.
break;
}
}
}
}
return object;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}