ITeye博客

利用反射机制模拟Hibernate的Session

wenbing2610 · 2012-03-20 22:59 · Struts · Hibernate · Web前端 · Hibernate · reflect · Markdown

Java代码 复制代码 收藏代码

  1. package com.quan.hibernate.model;
  2. import java.lang.reflect.Method;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.SQLException;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. /**
  10. * Session的模拟
  11. */
  12. public class create {
  13. String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=hibernate";
  14. String user = "sa";
  15. String password = "123";
  16. String tableName = "_Student";
  17. Map<String,String> cfs = new HashMap<String, String>();
  18. String[] methodNames;
  19. public create() {
  20. cfs.put("_id", "id");
  21. cfs.put("_name","name");
  22. cfs.put("_age", "age");
  23. methodNames = new String[cfs.size()];
  24. }
  25. public void save(Student s) throws Exception {
  26. String sql = createSQL();
  27. Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  28. Connection conn = DriverManager.getConnection(url, user, password);
  29. PreparedStatement ps = conn.prepareStatement(sql);
  30. for(int i = 0; i<methodNames.length;i++) {
  31. Method m = s.getClass().getMethod(methodNames[i]);
  32. Class r= m.getReturnType();
  33. if(r.getName() == "java.lang.String") {
  34. String returnValue = (String)m.invoke(s);
  35. ps.setString(i+1, returnValue);
  36. }
  37. if(r.getName() == "int") {
  38. Integer returnValue = (Integer)m.invoke(s);
  39. ps.setInt(i+1, returnValue);
  40. }
  41. }
  42. /*for(int i = 0; i<cfs.size(); i++) {
  43. ps.setXXX(s.getXXX);
  44. }*/
  45. ps.executeUpdate();
  46. ps.close();
  47. conn.close();
  48. }
  49. private String createSQL() {
  50. String str1 = "";
  51. String str2 = "";
  52. int index = 0;
  53. for(String s : cfs.keySet()) {
  54. String v = cfs.get(s);
  55. v= Character.toUpperCase(v.charAt(0)) + v.substring(1);
  56. methodNames[index] = "get" + v;
  57. str1 += s + ",";
  58. }
  59. str1 = str1.substring(0, str1.length()-1);
  60. for(int i = 0; i<cfs.size();i++) {
  61. str2 += "?,";
  62. }
  63. str2 = str2.substring(0, str2.length()-1);
  64. String sql = "insert into "+tableName+"("+str1+")"+"valses ("+str2+")";
  65. return sql;
  66. }
  67. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。