O/R Mapping:Sql语句编写并不是面向对象的和JDBC操作数据库很繁琐;O/R Mapping可以在对象和关系表之 间建立关联来简化编程,读取配置文件利用反射技术把对象拼成sql语句对数据库进行操作。
创建Session:
public class Session { String TABLENAME = "T_STUDENT"; Map<String, String> cfs = new HashMap<String, String>(); String[] methodNames; public Session() { cfs.put("id", "id"); cfs.put("name", "name"); cfs.put("age", "age"); methodNames = new String[cfs.size()]; } public void save(Student s) throws Exception { String sql = createSql(); Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/hibernate", "root", "*******"); PreparedStatement ps = conn.prepareStatement(sql); for (int i=0; i<methodNames.length; i++) { Method m = s.getClass().getMethod(methodNames[i]); Class r = m.getReturnType(); if ("java.lang.String".equals(r.getName())) { String returnValue = (String) m.invoke(s); ps.setString(i+1, returnValue); } if ("int".equals(r.getName())) { int returnValue = (Integer) m.invoke(s); ps.setInt(i+1, returnValue); } } ps.executeUpdate(); ps.close(); conn.close(); } private String createSql() { String str1 = ""; int index = 0; for (String s: cfs.keySet()) { String v = cfs.get(s); v = Character.toUpperCase(v.charAt(0)) + v.substring(1); methodNames[index] = "get" + v; index++; str1 += s + ","; } str1 = str1.substring(0, str1.length()-1); String str2 = ""; for (int i=0; i<cfs.size(); i++) { str2 += "?,"; } str2 = str2.substring(0, str2.length()-1); String sql = "insert into " + TABLENAME + "(" + str1 + ") values (" + str2 + ")"; return sql; } }
这样就可以直接调用session.save方法了:
Student s = new Student(); s.setId(3); s.setName("zhangsan"); s.setAge(8); Session session = new Session(); session.save(s);