目标:简单实现hibernate的save()方法。
1.首先我们假设我们从xml文件中已经获得了jdbc的连接,和属性和字段的映射表存入Map<String,String>中
2.创建一个实体类,和表Teacher(两者对应)
public class Teacher { private int id; private int height; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.创建一个Session类,里面包含save方法
import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.HashMap; import java.util.Map; public class Session { Map<String,String> map; String TableName = "teacher"; String[] MethodNames; //假设我们已经从配置文件中拿到了id name height映射关系 public Session() { map = new HashMap<String,String>(); map.put("id", "id"); map.put("name", "name"); map.put("height", "height"); MethodNames = new String[map.size()]; } // public String[] getMethods(Teacher t) throws NoSuchMethodException, SecurityException{ // //getAge // for(int i = 0;i<MethodNames.length;i++){ // String str = map.get(key) // str = Character.toUpperCase(str.charAt(0)) + str.substring(1); // MethodNames[i] = "get"+str; // System.out.println(MethodNames[i]); // } // return MethodNames; // } public void save(Teacher t) throws Exception{ t.getClass().forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/text02","root","6530033197"); String sql = creatSql(); PreparedStatement ps = con.prepareStatement(sql); /*ps.setInt(1,t.getId()); ps.setString(2,t.getName()); ps.setInt(3, t.getHeight()); */ Class c = t.getClass(); for(int i = 0;i<map.size();i++){ Method m = c.getMethod(MethodNames[i]); Class c1 = m.getReturnType(); System.out.println(c1.getName()); if(c1.getName().equals("java.lang.String")){ ps.setString(i+1, (String) m.invoke(t)); } if(c1.getName().equals("int")){ ps.setInt(i+1,(int)m.invoke(t)); } } ps.executeUpdate(); ps.close(); con.close(); } public String creatSql(){ String sql = ""; String str1 = ""; String str2 = ""; int index = 0; for(String str:map.keySet()){ String str3 = map.get(str); str3 = Character.toUpperCase(str.charAt(0)) + str.substring(1); MethodNames[index] = "get"+str3; //System.out.println(MethodNames[index]); str1 +=str+","; index++; } str1 = str1.substring(0, str1.length()-1); //System.out.println(str1); for(int x = 0;x<map.size();x++){ str2 += "?,"; } str2 = str2.substring(0, str2.length()-1); //System.out.println(str2); //insert into teacher("id","name","height")values(?,?,?); sql = "insert into "+TableName+"("+str1+") values("+str2+")"; System.out.println(sql); return sql; } }
4.用一个类做测试:
public class TeacherText { public static void main(String[] args) throws Exception { Teacher t = new Teacher(); t.setId(2); t.setHeight(180); t.setName("张大平"); Session s = new Session(); s.save(t); } }
完成,一个简单的save()方法就完成了,因为只是最简单的封装,所以代码很乱。