jdbc模拟hibernate-get
很想自己写模拟hibernate的封装,本人又是一个新手,能力有限,参考了网上资料,加上自己点修改。
方便自己的偷懒@!@
--连接
View Code
public Connection getConn() throws SQLException { MysqlDataSource ds = new MysqlDataSource(); ds.setUrl("jdbc:mysql://localhost:3306/test?user=root&password=1"); return (Connection) ds.getConnection(); }
--getObject
View Code
/** * 查询单个对象 * 使用:getObject("数据库表名 where id=1",Student.class); * @param sql 查询语句 * @param cls 类名.getClass() 要查询的类 * @return object */ public Object getObject(String sql, Class<?> cls) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Object obj = null; try { conn = this.getConn(); ps = (PreparedStatement) conn.prepareStatement("select * from "+sql); rs = (ResultSet) ps.executeQuery(); ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData(); int colCount = rsmd.getColumnCount(); obj = cls.newInstance(); if (rs.next()) { for (int i = 1; i <= colCount; i++) { String colName = rsmd.getColumnName(i); Object valType = rs.getObject(colName); Method met = obj.getClass().getMethod( getSetMethodName(colName), new Class[] { valType.getClass() }); met.invoke(obj, new Object[] { valType }); } } } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { this.colseAll(conn, ps, rs); } return obj; }
-- 相关方法
View Code
/** * 根据列名获取set方法 * * @param colN 列名 * @return */ private String getSetMethodName(String colN) { if (Character.isUpperCase(colN.charAt(0))) return "set" + colN; String str = colN.substring(0, 1); return "set" + colN.replaceFirst(str, str.toUpperCase()); }
希望有人指点,或是提供对应的资料参考,最好是可以看到又更好的写法,在楼中出现,感谢


浙公网安备 33010602011771号