用Java反射机制模拟hibernateJDBC操作


用Java反射机制模拟hibernateJDBC操作:

  1. package org.keyuan.resolve;  
  2.   
  3. import java.lang.annotation.Annotation;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.sql.Connection;  
  8. import java.sql.PreparedStatement;  
  9. import java.sql.ResultSet;  
  10. import java.sql.SQLException;  
  11. import java.text.SimpleDateFormat;  
  12. import java.util.ArrayList;  
  13. import java.util.Date;  
  14. import java.util.LinkedList;  
  15. import java.util.List;  
  16.   
  17. import javax.persistence.Column;  
  18. import javax.persistence.Entity;  
  19. import javax.persistence.Id;  
  20.   
  21. import org.apache.commons.beanutils.BeanUtils;  
  22. import org.keyuan.entity.Student;  
  23. import org.keyuan.util.DBConnectionUtil;  
  24.   
  25. /** 
  26.  *  
  27.  * 说明:使用java的反射机制模拟hibernate的session 
  28.  *  
  29.  * @author KeYuan 
  30.  *  
  31.  */  
  32. public class Session {  
  33.     private Connection conn = null;  
  34.     /** 
  35.      * 添加操作 
  36.      */  
  37.     public boolean save(Object entity) throws SecurityException,  
  38.             NoSuchMethodException, IllegalArgumentException,  
  39.             IllegalAccessException, SQLException, ClassNotFoundException {  
  40.         StringBuffer insertSql = new StringBuffer("insert into ");  
  41.         StringBuffer insertSqlValue = new StringBuffer();  
  42.         LinkedList<Object> insertParams = new LinkedList<Object>();  
  43.         Class<?> entityClass = entity.getClass();  
  44.         String tableName = getTableName(entityClass);  
  45.         insertSql.append(tableName);  
  46.         Field[] fields = entityClass.getDeclaredFields();  
  47.         insertSql.append("(");  
  48.         insertSqlValue.append(" values(");  
  49.         for (Field field : fields) {  
  50.             Annotation[] annotations = field.getAnnotations();  
  51.             String columnName = field.getName();  
  52.             // 查找当前属性上面是否有annotation注解   
  53.             Object[] findAnnotationResult = findAnnotation(annotations);  
  54.             Boolean isAnnotaionOverField = (Boolean) findAnnotationResult[0];  
  55.             // 如果在field中上面没有找到annotation,继续到get属性上去找有没有annotation   
  56.             if (!isAnnotaionOverField) {  
  57.                 // 拼接出field的get属性名   
  58.                 String getMethodName = "get"  
  59.                         + columnName.substring(01).toUpperCase()  
  60.                         + columnName.substring(1);  
  61.                 Method method = entityClass.getMethod(getMethodName,  
  62.                         new Class[] {});  
  63.                 // 同上判断这个方法有没有我们要找的annotation   
  64.                 annotations = method.getAnnotations();  
  65.                 findAnnotationResult = findAnnotation(annotations);  
  66.                 isAnnotaionOverField = (Boolean) findAnnotationResult[0];  
  67.             }  
  68.             // 判断通过前面两步操作有没有在当前的字段上面找到有效的annotation   
  69.             if (!isAnnotaionOverField)  
  70.                 continue;  
  71.             // 到这步说明在当前的字段或字段get属性上面找到有效的annotation了   
  72.             // 拼接insert sql 语句   
  73.             String tempColumnName = (String) findAnnotationResult[1];  
  74.             if (tempColumnName != null && !"".equals(tempColumnName))  
  75.                 columnName = tempColumnName;  
  76.             insertSql.append(columnName).append(",");// 前面列名部分   
  77.             insertSqlValue.append("?,"); // 后面?参数部分   
  78.             // 得到对应的字段值并记录,作为以后?部分值   
  79.             field.setAccessible(true);  
  80.             insertParams.add(field.get(entity));  
  81.         }  
  82.         insertSql.replace(insertSql.lastIndexOf(","), insertSql.length(), ")");  
  83.         insertSqlValue.replace(insertSqlValue.lastIndexOf(","), insertSqlValue  
  84.                 .length(), ")");  
  85.         // 拼接两部分的sql   
  86.         insertSql.append(insertSqlValue);  
  87.         System.out.println(insertSql);  
  88.         // 执行添加操作了   
  89.         conn = DBConnectionUtil.getConnection();  
  90.         PreparedStatement prep = conn.prepareStatement(insertSql.toString());  
  91.         int i = 1;  
  92.         for (Object param : insertParams) {  
  93.             if (param instanceof Date) {  
  94.                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
  95.                 java.sql.Date date = java.sql.Date.valueOf(dateFormat  
  96.                         .format(param));  
  97.                 prep.setDate(i, date);  
  98.             } else {  
  99.                 prep.setObject(i, param);  
  100.             }  
  101.             i++;  
  102.         }  
  103.         if (prep.executeUpdate() > 0)  
  104.             return true;  
  105.         return false;  
  106.     }  
  107.     /** 
  108.      * 得到表的真实名 
  109.      */  
  110.     private String getTableName(Class<?> entityClass) {  
  111.         String tableName = entityClass.getSimpleName();  
  112.         if (entityClass.isAnnotationPresent(Entity.class)) {  
  113.             Entity entityAnnotation = entityClass.getAnnotation(Entity.class);  
  114.             String tempTableName = entityAnnotation.name();  
  115.             if (tempTableName != null && !"".equals(tempTableName))  
  116.                 tableName = tempTableName;  
  117.         }  
  118.         return tableName;  
  119.     }  
  120.     /** 
  121.      * 查询字段或是属性上面有没有有效annotation 
  122.      */  
  123.     private Object[] findAnnotation(Annotation[] annotations) {  
  124.         Object[] resurlt = new Object[] { falsenull };  
  125.         if (annotations.length == 0)  
  126.             return resurlt;  
  127.         for (Annotation annotation : annotations) {  
  128.             // 我们假定当他找到下列标签中任何一个标签就认为是要与数据库映射的   
  129.             if (annotation instanceof Column) {  
  130.                 resurlt[0] = true;  
  131.                 Column column = (Column) annotation;  
  132.                 String tempColumnName = column.name();  
  133.                 if (tempColumnName != null && !"".equals(tempColumnName))  
  134.                     resurlt[1] = tempColumnName;  
  135.             }  
  136.         }  
  137.         return resurlt;  
  138.     }  
  139.   
  140.     /** 
  141.      *  修改操作 
  142.      */  
  143.     public boolean update(Object entity) throws SecurityException,  
  144.             NoSuchMethodException, IllegalArgumentException,  
  145.             IllegalAccessException, ClassNotFoundException, SQLException {  
  146.         // update stuInfo stu set stu.stuName1='ddd' where stu.stuid=43   
  147.         StringBuffer updateSql = new StringBuffer("update ");  
  148.         LinkedList<Object> updateParams = new LinkedList<Object>();  
  149.         String primaryKeyColumn = "";  
  150.         Integer primaryParam = null;  
  151.         Class<?> entityClass = entity.getClass();  
  152.         String tableName = getTableName(entityClass);  
  153.   
  154.         updateSql.append(tableName).append(" tab set ");  
  155.         Field[] fields = entityClass.getDeclaredFields();  
  156.         for (Field field : fields) {  
  157.             String columnName = field.getName();  
  158.             Annotation[] annotations = field.getAnnotations();  
  159.             // 判断是否是主键   
  160.             boolean isfindPrimarykey = false;  
  161.             for (Annotation annotation : annotations) {  
  162.                 if (annotation instanceof Id) {  
  163.                     primaryKeyColumn = field.getName();  
  164.                     field.setAccessible(true);  
  165.                     primaryParam = (Integer) field.get(entity);  
  166.                     isfindPrimarykey = true;  
  167.                     break;  
  168.                 }  
  169.   
  170.             }  
  171.             if (isfindPrimarykey)  
  172.                 continue;  
  173.             Object[] findAnnotationResult = findAnnotation(annotations);  
  174.             boolean isAnnotaionOverField = (Boolean) findAnnotationResult[0];  
  175.             if (!isAnnotaionOverField) {  
  176.                 String getMethodName = "get"  
  177.                         + columnName.substring(01).toUpperCase()  
  178.                         + columnName.substring(1);  
  179.                 Method method = entityClass.getMethod(getMethodName,  
  180.                         new Class[] {});  
  181.                 annotations = method.getAnnotations();  
  182.                 findAnnotationResult = findAnnotation(annotations);  
  183.                 isAnnotaionOverField = (Boolean) findAnnotationResult[0];  
  184.             }  
  185.             if (!isAnnotaionOverField)  
  186.                 continue;  
  187.             String tempColumnName = (String) findAnnotationResult[1];  
  188.             if (tempColumnName != null && !"".equals(tempColumnName))  
  189.                 columnName = tempColumnName;  
  190.             updateSql.append("tab.").append(columnName).append("=?,");  
  191.             field.setAccessible(true);  
  192.             updateParams.add(field.get(entity));  
  193.         }  
  194.         updateSql.replace(updateSql.lastIndexOf(","), updateSql.length(), "");  
  195.         updateSql.append(" where tab.").append(primaryKeyColumn).append("=?");  
  196.         System.out.println(updateSql);  
  197.   
  198.         conn = DBConnectionUtil.getConnection();  
  199.         PreparedStatement prep = conn.prepareStatement(updateSql.toString());  
  200.         int i = 1;  
  201.         for (Object param : updateParams) {  
  202.             if (param instanceof Date) {  
  203.                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
  204.                 java.sql.Date date = java.sql.Date.valueOf(dateFormat  
  205.                         .format(param));  
  206.                 prep.setDate(i, date);  
  207.             } else {  
  208.                 prep.setObject(i, param);  
  209.             }  
  210.             i++;  
  211.         }  
  212.         prep.setInt(i, primaryParam);  
  213.         if (prep.executeUpdate() > 0)  
  214.             return true;  
  215.         return false;  
  216.     }  
  217.   
  218.     /** 
  219.      *  删除操作 
  220.      */  
  221.     public boolean delete(Object entity) throws IllegalArgumentException,  
  222.             IllegalAccessException, ClassNotFoundException, SQLException {  
  223.         // delete from stuInfo stu where stu.stuid=43   
  224.         StringBuffer deleteSql = new StringBuffer("delete from ");  
  225.         Integer primaryParam = null;  
  226.         Class<?> entityClass = entity.getClass();  
  227.         String tableName = getTableName(entityClass);  
  228.         deleteSql.append(tableName).append(" tab ").append("where ");  
  229.         Field[] fields = entityClass.getDeclaredFields();  
  230.         for (Field field : fields) {  
  231.             Annotation[] annotations = field.getAnnotations();  
  232.             boolean isfindPrimary = false;  
  233.             for (Annotation annotation : annotations) {  
  234.                 if (annotation instanceof Id) {  
  235.                     deleteSql.append("tab.").append(field.getName()).append(  
  236.                             "=?");  
  237.                     field.setAccessible(true);  
  238.                     primaryParam = (Integer) field.get(entity);  
  239.                     isfindPrimary = true;  
  240.                     break;  
  241.                 }  
  242.             }  
  243.             if (isfindPrimary)  
  244.                 break;  
  245.         }  
  246.         conn = DBConnectionUtil.getConnection();  
  247.         System.out.println(deleteSql.toString());  
  248.         PreparedStatement prep = conn.prepareStatement(deleteSql.toString());  
  249.         prep.setInt(1, primaryParam);  
  250.         if (prep.executeUpdate() > 0)  
  251.             return true;  
  252.         return false;  
  253.     }  
  254.   
  255.     /** 
  256.      * 根据Id查询某个实体对象 
  257.      */  
  258.     public <T> T get(Class<T> entityClass, Integer id)  
  259.             throws ClassNotFoundException, SQLException,  
  260.             InstantiationException, IllegalAccessException, SecurityException,  
  261.             NoSuchMethodException, IllegalArgumentException,  
  262.             InvocationTargetException {  
  263.         T entity = null;  
  264.         StringBuffer selectByIdSql = new StringBuffer("select * from ");  
  265.         String tableName = getTableName(entityClass);  
  266.         selectByIdSql.append(tableName).append(" tab where tab.");  
  267.         Field[] fields = entityClass.getDeclaredFields();  
  268.         for (Field field : fields) {  
  269.             Annotation[] annotations = field.getAnnotations();  
  270.             boolean isfindPrimaryfield = false;  
  271.             String columnName = field.getName();  
  272.             for (Annotation annotation : annotations) {  
  273.                 if (annotation instanceof Id) {  
  274.                     selectByIdSql.append(columnName).append("=?");  
  275.                     isfindPrimaryfield = true;  
  276.                     break;  
  277.                 }  
  278.             }  
  279.             if (!isfindPrimaryfield) {  
  280.                 String getMethodName = "get"  
  281.                         + columnName.substring(01).toUpperCase()  
  282.                         + columnName.substring(1);  
  283.                 Method getMethod = entityClass.getMethod(getMethodName,  
  284.                         new Class[] {});  
  285.                 annotations = getMethod.getAnnotations();  
  286.                 for (Annotation annotation : annotations) {  
  287.                     if (annotation instanceof Id) {  
  288.                         selectByIdSql.append(columnName).append("=?");  
  289.                         isfindPrimaryfield = true;  
  290.                         break;  
  291.                     }  
  292.                 }  
  293.             }  
  294.             if (isfindPrimaryfield)  
  295.                 break;  
  296.   
  297.         }  
  298.         System.out.println(selectByIdSql.toString());  
  299.         conn = DBConnectionUtil.getConnection();  
  300.         PreparedStatement prep = conn  
  301.                 .prepareStatement(selectByIdSql.toString());  
  302.         prep.setInt(1, id);  
  303.         ResultSet result = prep.executeQuery();  
  304.         while (result.next()) {  
  305.             entity = setData2Entity(entityClass, fields, result);  
  306.         }  
  307.         return entity;  
  308.     }  
  309.     /** 
  310.      *装result中的数据据,用反射加入到对应的实体中  
  311.      */  
  312.     private <T> T setData2Entity(Class<T> entityClass, Field[] fields,  
  313.             ResultSet result) throws InstantiationException,  
  314.             IllegalAccessException, NoSuchMethodException, SQLException,  
  315.             InvocationTargetException {  
  316.         // 把数据组拼到对象中去   
  317.         T entity = entityClass.newInstance();  
  318.         for (Field field : fields) {  
  319.             String fieldName = field.getName();  
  320.             String columnName = fieldName;  
  321.             Annotation[] annotations = field.getAnnotations();  
  322.             Object[] findAnnotationResult = findAnnotation(annotations);  
  323.             boolean isfindAnotation = (Boolean) findAnnotationResult[0];  
  324.             if (!isfindAnotation) {  
  325.                 String getMethodName = "get"  
  326.                         + fieldName.substring(01).toUpperCase()  
  327.                         + fieldName.substring(1);  
  328.                 Method method = entityClass.getMethod(getMethodName,  
  329.                         new Class[] {});  
  330.                 annotations = method.getAnnotations();  
  331.                 findAnnotationResult = findAnnotation(annotations);  
  332.                 isfindAnotation = (Boolean) findAnnotationResult[0];  
  333.             }  
  334.             String tempColumnName = (String) findAnnotationResult[1];  
  335.             if (tempColumnName != null && !"".equals(tempColumnName))  
  336.                 columnName = tempColumnName;  
  337.             Object value = result.getObject(columnName);  
  338.             BeanUtils.setProperty(entity, fieldName, value);  
  339.         }  
  340.         return entity;  
  341.     }  
  342.   
  343.     /** 
  344.      * 分页查询所有记录 
  345.      **/  
  346.     public <T> List<T> getPaging(Class<T> entityClass, int firstIndex,  
  347.             int maxResult) throws ClassNotFoundException, SQLException,  
  348.             InstantiationException, IllegalAccessException,  
  349.             NoSuchMethodException, InvocationTargetException {  
  350.         List<T> results = new ArrayList<T>();  
  351.         StringBuffer pageIngSql = new StringBuffer(  
  352.                 "select * from (select rownum rn,tab.* from ");  
  353.         String tableName = getTableName(entityClass);  
  354.         pageIngSql.append(tableName).append(" tab ) where rn between ? and ?");  
  355.         System.out.println(pageIngSql.toString());  
  356.         conn = DBConnectionUtil.getConnection();  
  357.         PreparedStatement prep = conn.prepareStatement(pageIngSql.toString());  
  358.   
  359.         prep.setInt(1, firstIndex);  
  360.         prep.setInt(2, firstIndex + maxResult);  
  361.         ResultSet result = prep.executeQuery();  
  362.         Field[] fields = entityClass.getDeclaredFields();  
  363.         while (result.next()) {  
  364.             T entity = setData2Entity(entityClass, fields, result);  
  365.             results.add(entity);  
  366.         }  
  367.         return results;  
  368.     }  
  369.   
  370.     /** 
  371.      * 得到总页数 
  372.      */  
  373.     public <T> int getCount(Class<T> entityClass)  
  374.             throws ClassNotFoundException, SQLException {  
  375.         int count = 0;  
  376.         StringBuffer countSql = new StringBuffer("select count(*) count from ");  
  377.         String tableName = getTableName(entityClass);  
  378.         countSql.append(tableName);  
  379.         System.out.println(countSql.toString());  
  380.         conn = DBConnectionUtil.getConnection();  
  381.         PreparedStatement prep = conn.prepareStatement(countSql.toString());  
  382.         ResultSet result = prep.executeQuery();  
  383.         if (result.next()) {  
  384.             count = result.getInt("count");  
  385.         }  
  386.         return count;  
  387.     }  
  388.     //测试   
  389.     public static void main(String[] args) throws SecurityException,  
  390.             IllegalArgumentException, NoSuchMethodException,  
  391.             IllegalAccessException, SQLException, ClassNotFoundException,  
  392.             InstantiationException, InvocationTargetException {  
  393.         Session session = new Session();  
  394.         Student student = new Student();  
  395.         student.setStuId(2);  
  396.         student.setStuName("hhhh");  
  397.         student.setBirthday(new Date());  
  398.         /* 
  399.         if (session.save(student)) { 
  400.             System.out.println("添加成功"); 
  401.         } else { 
  402.             System.out.println("添加失败"); 
  403.         } 
  404.         */  
  405.         /* 
  406.          * student.setStuId(43);  
  407.          * if (session.update(student)) { 
  408.          *  System.out.println("修改成功");  
  409.          * }  
  410.          * else { 
  411.          *  System.out.println("修改失败"); 
  412.          *   } 
  413.          */  
  414.   
  415.         /* 
  416.          * student.setStuId(42);  
  417.          * if (session.delete(student)) { 
  418.          *  System.out.println("删除成功"); 
  419.          *  } else {  
  420.          *  System.out.println("删除失败"); 
  421.          *   } 
  422.          */  
  423.         /* 
  424.          * 根据id查询 student = session.get(Student.class, 41); 
  425.          * System.out.println(student.getStuId() + " name:" + 
  426.          * student.getStuName() + "  birthday:" + student.getBirthday()); 
  427.          */  
  428.   
  429.         /* 
  430.          * 分页查询 
  431.          */  
  432.         int currentPage = 1;  
  433.         int maxResult = 2;  
  434.         int count = session.getCount(Student.class);  
  435.         int countPage = count / maxResult == 0 ? count / maxResult : count  
  436.                 / maxResult + 1;  
  437.         int firstIndex = (currentPage - 1) * maxResult+1;  
  438.         List<Student> pagingList = session.getPaging(Student.class,  
  439.                 firstIndex, maxResult);  
  440.         System.out  
  441.                 .println("总页数:" + countPage + " \t 当前第 " + currentPage + " 页");  
  442.         System.out.println("编号\t姓名\t出生年日");  
  443.         for (Student student2 : pagingList) {  
  444.             System.out.println(student2.getStuId() + "\t"  
  445.                     + student2.getStuName() + "\t" + student2.getBirthday());  
  446.         }     
  447.     }  
  448. }  
  449. 测试实体类:Student  
  450. package org.keyuan.entity;  
  451.   
  452. import java.util.Date;  
  453.   
  454. import javax.persistence.Column;  
  455. import javax.persistence.Entity;  
  456. import javax.persistence.Id;  
  457.   
  458. @Entity(name="stuInfo")  
  459. public class Student {  
  460.     @Id  
  461.     private int stuId;  
  462.     private String stuName;  
  463.     private Date birthday;  
  464.     @Id  
  465.     public int getStuId() {  
  466.         return stuId;  
  467.     }  
  468.     public void setStuId(int stuId) {  
  469.         this.stuId = stuId;  
  470.     }  
  471.     @Column(name="stuName1")  
  472.     public String getStuName() {  
  473.         return stuName;  
  474.     }  
  475.     public void setStuName(String stuName) {  
  476.         this.stuName = stuName;  
  477.     }  
  478.     @Column(name="birthday")   
  479.     public Date getBirthday() {  
  480.         return birthday;  
  481.     }  
  482.     public void setBirthday(Date birthday) {  
  483.         this.birthday = birthday;  
  484.     }  
  485. }  
  486. 连接工具类:DbConnectionUtil  
  487. package org.keyuan.util;  
  488.   
  489. import java.sql.Connection;  
  490. import java.sql.DriverManager;  
  491. import java.sql.SQLException;  
  492.   
  493. public class DBConnectionUtil {  
  494.     private static final String DRIVER= "Oracle.jdbc.driver.OracleDriver";  
  495.     private static final String URL = "jdbc:oracle:thin:@localhost:1521:KEYUAN";  
  496.     private static final String PASSWORD = "test";  
  497.     private static final String USER = "test";  
  498.       
  499.     private static Class<?> driverClass;  
  500.     static{  
  501.         try {  
  502.             initDriver();  
  503.         } catch (ClassNotFoundException e) {  
  504.             e.printStackTrace();  
  505.         }  
  506.     }  
  507.     private static void initDriver() throws ClassNotFoundException{  
  508.             driverClass=Class.forName(DRIVER);  
  509.     }  
  510.     public static Connection getConnection() throws ClassNotFoundException, SQLException{  
  511.         if(driverClass==null)  
  512.             initDriver();  
  513.       return DriverManager.getConnection(URL,USER,PASSWORD);  
  514.     }  
  515. }  

相关内容