简单jdbc包装orm类
(1)首先创建一个pojo对象
package org.hibernate.reflect.util;
import java.util.HashMap;
import java.util.Map;
public class Student {
public static String tableName = "student";
private int id;
private int age;
private String name;
public Student() {
super();
}
public Student(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String,String> getField(){
Map<String,String> params = new HashMap<String, String>();
params.put("id", "id");
params.put("age", "age");
params.put("name", "name");
return params;
}
}
(2)创建获取jdbc链接的类
package org.hibernate.reflect.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.74.10:3306/fastknow_lady","fastknow_lady","fastknow_lady");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
(3)模拟hibernate类
package org.hibernate.reflect.util;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class HibernateTemplate<T> {
String[] methodNames;
public HibernateTemplate(){
}
public String complieSQL(Student s){
methodNames = new String[s.getField().size()];
String value = "";
String name = "";
int index = 0;
for(String key : s.getField().keySet()){
String m = s.getField().get(key);
methodNames[index++] = "get" + Character.toUpperCase(m.charAt(0)) + m.substring(1);
name += key + ",";
}
for(int i=0;i<s.getField().size();i++){
value += "?,";
}
name = name.substring(0,name.length()-1);
value = value.substring(0,value.length()-1);
String sql = "insert " + s.tableName + "(" + name + ") values(" + value + ")";
return sql;
}
public void save(Student s){
String sql = complieSQL(s);
try {
Connection conn = Connector.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
for(int i=0;i<methodNames.length;i++){
Method m = s.getClass().getMethod(methodNames[i]);
Class returnType = m.getReturnType();
if(returnType.getName().equals("int")){
Integer returnValue = (Integer)m.invoke(s);
ps.setInt(i+1, returnValue);
}else if(returnType.getName().equals("java.lang.String")){
String returnValue = (String)m.