first model:
student.java:
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;
}
}
then 原理模擬:
Session.java:
public class Session {
String tableName = "_Student";
Map<String,String> cfs = new HashMap<String ,String>();
String [] methodNames = new String[cfs.size()];
public Session(){
cfs.put("_id", "id");
cfs.put("_name", "name");
cfs.put("_age", "age");
methodNames = new String[cfs.size()];
}
public void save(Student s) {
String sql = createSQL();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate", "root", "root");//這裏是我的數據庫連接信息
PreparedStatement ps = conn.prepareStatement(sql);
for(int i = 0;i<methodNames.length;i++){
try {
Method m = s.getClass().getMethod(methodNames[i]);//利用反射機制,得到返回值的類型。
Class r = m.getReturnType(); //取得返回值類型。
if(r.getName().equals("java.lang.String")){ //比較。
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);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
ps.executeUpdate();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
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;
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 + ");" ;
return sql;
}
}
lastest main:
StudentTest.java:
public class StudentTest {
public static void main(String[]args){
Student s = new Student();
s.setId(2);
s.setName("s2");
s.setAge(2);
Session session = new Session();
session.save(s);
}
}