- package com.quan.hibernate.model;
- import java.lang.reflect.Method;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * Session的模拟
- */
- public class create {
- String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=hibernate";
- String user = "sa";
- String password = "123";
- String tableName = "_Student";
- Map<String,String> cfs = new HashMap<String, String>();
- String[] methodNames;
- public create() {
- cfs.put("_id", "id");
- cfs.put("_name","name");
- cfs.put("_age", "age");
- methodNames = new String[cfs.size()];
- }
- public void save(Student s) throws Exception {
- String sql = createSQL();
- Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
- Connection conn = DriverManager.getConnection(url, user, password);
- PreparedStatement ps = conn.prepareStatement(sql);
- for(int i = 0; i<methodNames.length;i++) {
- Method m = s.getClass().getMethod(methodNames[i]);
- Class r= m.getReturnType();
- if(r.getName() == "java.lang.String") {
- String returnValue = (String)m.invoke(s);
- ps.setString(i+1, returnValue);
- }
- if(r.getName() == "int") {
- Integer returnValue = (Integer)m.invoke(s);
- ps.setInt(i+1, returnValue);
- }
- }
- /*for(int i = 0; i<cfs.size(); i++) {
- ps.setXXX(s.getXXX);
- }*/
- 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 + ",";
- }
- str1 = str1.substring(0, str1.length()-1);
- for(int i = 0; i<cfs.size();i++) {
- str2 += "?,";
- }
- str2 = str2.substring(0, str2.length()-1);
- String sql = "insert into "+tableName+"("+str1+")"+"valses ("+str2+")";
- return sql;
- }
- }
利用反射机制模拟Hibernate的Session
最新推荐文章于 2021-02-28 18:11:22 发布