Hibernate相当于将我们操作数据库的语句转化成java擅长的面向对象编程,是对一系列面向关系的编程的封装。
通过解析xml文件得到model(也就是创建的与数据库相对应的实体类)和数据库一一对应的关系,比如说id,name等等。将这些属性拼接到sql语句中,比如insert into user(id,name) value(?,?),接着用到java中反射机制,找到属性对应的类型,获取要插入的具体的值,最后执行PrepareStatement类的方法
具体看下面的代码:
package hong.hibernate.daoimpl;
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 hong.hibernate.model.User;
public class Session {
// tableName,map是这个类的成员变量,成员变量的只一般通过set方法确定,也可通过累的构造器确定
String tableName = "_user";
Map<String, String> map = new HashMap<String, String>();
String[] methodName = null;
public Session() {
map.put("_id", "id");
map.put("_name", "name");
map.put("_age", "age");
methodName = new String[map.size()];
}
public void save(User u) 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<methodName.length; i++){
//通过反射找到methodName中的字符串对应的u中的方法
Method m = u.getClass().getMethod(methodName[i]);
//得到相应方法的返回值类型
Class t = m.getReturnType();
//针对不同的返回值类型,也就是数据库中不同字段的类型,选择不同的PrepareStatement的方法
if(t.getName().equals("java.lang.String")){
String returnValue = (String)m.invoke(u);
ps.setString(i+1, returnValue);
}
if(t.getName().equals("int")){
Integer returnValue = (Integer)m.invoke(u);
ps.setInt(i+1, returnValue);
}
}
ps.executeUpdate();
ps.close();
conn.close();
}
private String createSql() {
int index = 0;
String str1 = "";
//遍历map中key的值,也就是对应数据库中的列的名称,_id _name _age
for (String s : map.keySet()) {
//得到key对应的实体类中的属性,id name age
String v = map.get(s);
System.out.println(v);
//将v的值进行首字母大写
v = Character.toUpperCase(v.charAt(0)) + v.substring(1);
//拼接成实体类中的get方法,并将其放入methodName数组中
methodName[index] = "get" + v;
System.out.println(methodName[index]);
str1 += s + ",";
index++;
}
str1 = str1.substring(0, str1.length() - 1);
System.out.println(str1);
String str2 = "";
for (int i = 0; i < map.size(); i++) {
str2 += "?,";
}
System.out.println(str2);
str2 = str2.substring(0, str2.length() - 1);
String sql = "insert into " + tableName + "(" + str1 + ") value ("
+ str2 + ")";
System.out.println(sql);
return sql;
}
}
封装之后就可以像Hibernate那样直接调用session.save(u);直接将u插入到数据库中去,从而将面向关系编程封装成面向对象编程。
例如以下的main方法:
package hong.test;
import hong.hibernate.daoimpl.Session;
import hong.hibernate.model.User;
public class User_Test {
public static void main(String[] args) throws Exception{
User u = new User("hong1",23);
Session session = new Session();
session.save(u);
}
}