本文使用java原生的JDBC实现ORM思想。
需要使用Apache commons中的两个类库、一个mysql数据库驱动:

实现代码如下:
public <T> T getObject(Class<T> clz, String sql, Object... args)
throws SQLException, IllegalAccessException, InvocationTargetException, InstantiationException {
Connection con = null;
PreparedStatement ps = null;
ResultSet res = null;
con = jdbcUtil.createcon();//获取mysql连接
ps = con.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
ps.setObject(i + 1, args[i]);
}
res = ps.executeQuery();
ResultSetMetaData resm = res.getMetaData();
HashMap<String, Object> map = new HashMap<String, Object>();
if (res.next())
{
for (int i = 0; i < resm.getColumnCount(); i++) {
String label = resm.getColumnLabel(i + 1);
Object value = res.getObject(label);
map.put(label, value);
}
}
Set<Entry<String, Object>> set = map.entrySet();
T p = clz.newInstance();
for (Entry<String, Object> entry : set)
{
String key = entry.getKey();
Object value = entry.getValue();
BeanUtils.setProperty(p, key, value);
}
res.close();
ps.close();
con.close();
return p;
}Person类:
public class Person
{
Integer id;
String name;
String phone;
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}测试代码:
@Test
public void test1() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException,
InstantiationException {
Person p = getObject(Person.class, "select * from person where id=5");
System.out.println(p);
}运行结果:

0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复