模擬hibernate實現的JAVA源碼
實體類:
package com.zzk.hibernate.model; public class Student { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
測試類:
package com.zzk.hibernate.model.test; import com.zzk.hibernate.model.Session; import com.zzk.hibernate.model.Student; import com.zzk.hibernate.model.Student; public class StudentTest { public static void main(String[] args) throws Exception{ Student s = new Student(); s.setId(3); s.setName("s3"); s.setAge(3); Session session = new Session(); session.save(s); } }
模擬Session的方法:
package com.zzk.hibernate.model; 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 { String tableName = "_Student"; Map<String,String> cfs = new HashMap<String,String>(); String[] methodNames;//用於存入實體類中的get方法數組 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();//創建SQL串 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate","root","root"); PreparedStatement ps = conn.prepareStatement(sql); // for(int i = 0; i < methodNames.length; i++){ Method m = s.getClass().getMethod(methodNames[i]);//返回一個 Method 對象,它反映此 Class 對象所表示的類或接口的指定公共成員方法 Class r = m.getReturnType();//返回一個 Class 對象,該對象描述了此 Method 對象所表示的方法的正式返回類型 if(r.getName().equals("java.lang.String")) { //對帶有指定參數的指定對象調用由此 Method 對象表示的底層方法。 //個別參數被自動解包,以便與基本形參相匹配,基本參數和引用參數都隨需服從方法調用轉換 String returnValue = (String)m.invoke(s); ps.setString(i + 1, returnValue); } if(r.getName().equals("int")) { Integer returnValue = (Integer)m.invoke(s); ps.setInt(i + 1, returnValue); } // if(r.getName().equals("java.lang.String")) { // String returnValue = (String)m.invoke(s); // ps.setString(i + 1, returnValue); // } System.out.println(m.getName() + "¦" + r.getName()); } 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;//拚實體類成員屬性的getter方法 str1 += s + ",";//根據表中字段名拚成字段串 index ++; } 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 + ")"; System.out.println(sql); return sql; } }
最後更新:2017-04-02 17:28:38