本文使用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++代码)(大数乘法也是可以避免的么hhhh)浏览:1596 |
点我有惊喜!你懂得!浏览:4146 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:584 |
高精度加法 (C++代码)(大数加法)浏览:1008 |
C语言训练-字符串正反连接 (C语言代码)浏览:665 |
C语言程序设计教程(第三版)课后习题8.9 (Java代码)浏览:1415 |
【亲和数】 (C语言代码)浏览:932 |
最长单词 (C语言代码)浏览:1498 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:673 |
C语言程序设计教程(第三版)课后习题10.4 (C语言代码)浏览:943 |