lvxuzhou


私信TA

用户名:lvxuzhou

访问量:97339

签 名:

lvxuzhou

等  级
排  名 48
经  验 11191
参赛次数 0
文章发表 56
年  龄 0
在职情况 学生
学  校 西安
专  业

  自我简介:

本文使用java原生的JDBC实现ORM思想。

需要使用Apache commons中的两个类库、一个mysql数据库驱动:

QQ图片20180709165116.png

实现代码如下:

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);
}

运行结果:

QQ图片20180709165714.png

 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区