JDBC ORM

相当头疼,郁闷。
SQL> desc person;
名称 是否为空? 类型
----------------------------------------- -------- ---------------
ID NOT NULL NUMBER
NAME VARCHAR2(20)
BIRTHDAY DATE
MONEY NUMBER
这是person的表结构。
我想利用JDBC进行ORM测试,User类如下:

import java.sql.Date;

public class User {
private int id;
private String name;
private Date birthday;
private int money;

public User() {

}

@Override
public String toString() {
return "id=" + this.id + " name=" + this.name + " birthday="
+ this.birthday + " money=" + this.money;
}


public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public int getMoney() {
return money;
}

public void setMoney(int money) {
this.money = money;
}
}

ORMTest表如下:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class ORMTest {
public static void main(String[] args) throws Exception {
User user = (User)getObject("select id,name,birthday,money from person where id = 3",User.class);
System.out.println(user);
Bean bean = (Bean)getObject("select id,name,birthday,money from person where id = 3",Bean.class);
System.out.println(bean);
}

static Object getObject(String sql,Class clazz) throws InvocationTargetException,IllegalArgumentException, Exception {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
con = JdbcUtil.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();

int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for (int i = 0; i < count; i++) {
String str = rsmd.getColumnName(i + 1);
str = str.substring(0, 1) + str.toLowerCase().substring(1);
colNames[i] = str;
}
Object object = null;
Method[] method = clazz.getMethods();
if (rs.next()) {
object = clazz.newInstance();
for (int i = 1; i <= colNames.length; i++) {
String colName = colNames[i - 1];
String methodName = "set" + colName;
for (Method m : method) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));
}
}
}
}
return object;
} finally {
JdbcUtil.close(rs, ps, con);
}

}

}

为什么总是提醒IllegalArgumentException,说是参数类型不匹配。如果我把User类中的int类型的 id和money改成Object类型就可以得到结果,为什么Date和String可以直接转换啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值