ORMAPPING 简单实现
程序员文章站
2022-06-04 15:07:13
...
package com.nintenyun.hibernate.model; public class Teacher { private int id; private String name; private String title; 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 String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
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;
import com.nintenyun.hibernate.model.Teacher;
public class Session {
Map<String,String> cfs = new HashMap<String,String>();
String[] methodNames ;
String tableName = "_teacher";
public Session(){
cfs.put("_id","id");
cfs.put("_name","name");
cfs.put("_title","title");
methodNames = new String[cfs.size()];
}
public void save(Teacher t) throws Exception{
String sql = createSQL();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/hibernate_or","root","nin");
PreparedStatement ps = conn.prepareStatement(sql);
for(int i = 0;i<methodNames.length ; i++){
Method m = t.getClass().getMethod(methodNames[i]);
Class r = m.getReturnType();
if(r.getName().equals("java.lang.String")){
String returnValue = (String)m.invoke(t);
ps.setString(i+1,returnValue);
}
if(r.getName().equals("int")){
Integer returnValue = (Integer)m.invoke(t);
ps.setInt(i+1,returnValue);
}
}
ps.executeUpdate();
ps.close();
conn.close();
}
private String createSQL() {
String str1 = "" ;
String str2 = "" ;
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);
for(int i = 0 ;i<cfs.size(); i++){
str2 = str2 + "?,";
}
str2 = str2.substring(0,str2.length()-1);
//System.out.println(str2);
String sql = "insert into " + tableName + "(" + str1 + ")" + " values " + "(" + str2 + ")" ;
System.out.println(sql);
return sql;
}
}
import com.nintenyun.hibernate.model.Student;
import com.nintenyun.hibernate.model.Teacher;
public class TeacherTest {
public static void main(String[] args) throws Exception{
Teacher t = new Teacher();
Session session = new Session();
t.setId(1);
t.setName("pass");
t.setTitle("master");
session.save(t);
}
}
上一篇: 老人高血脂怎么办 四个办法帮助你
下一篇: 老人的安全问题要注意哪些 这些方面要注意