import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import java.sql.*;
import com.zjh.hibernate.model.Student; //自己定义的Student类,包含int id,String name,int age 这三个成员变量
public class Session {
String tableName;
Map<String, String> cfs = new HashMap<String, String>(); //cfs意思是configurations
String[] methodNames;
public Session() {
cfs.put("_id", "id");
cfs.put("_name", "name");
cfs.put("_age", "age");
tableName = "_student"; //这里默认已经读到配置文件,得到了映射关系
methodNames = new String[cfs.size()];
}
public void save(Student s) throws Exception{
String sql = createSQL();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/hibernate","root","root");
PreparedStatement ps = conn.prepareStatement(sql);
for(int i=0;i<methodNames.length;i++) {
String mName = methodNames[i];
Method m = s.getClass().getMethod(mName);
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")) {
int returnValue = (Integer)m.invoke(s);
ps.setInt(i+1, returnValue);
}
}
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 = v.substring(0, 1).toUpperCase() + v.substring(1);
methodNames[index++] = "get" + v;
str1 += s + ",";
}
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;
}
}
自己实现的Hibernate insert语句自动生成的方法。假设已经从配置文件中读到映射关系,并且数据库中存在名为"_student"的表。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于