注解+反射+JDBC,实现一个简易的泛型DAO接口

来源:互联网 发布:ios哪个vpn好用 知乎 编辑:程序博客网 时间:2024/05/27 19:28

 

 

一、实现思路

      1、定义3个Annotation(注解):Entity、Id、Column,Entity作用于Type级别,用于标识JavaBean与数据库表名的映射关系。Id作用于Field级别,用于标识JavaBean中ID属性与表中ID字段的映射关系,Column作用于Field级别,用于标识JavaBean中除ID属性外的其它属性与表中字段的映射关系。

     2、在Dao实现类中,通过反射API获得JavaBean中注解和属性的信息,如:表名、字段。JavaBean属性的名称、数据类型等信息。然后将这些信息拼接成一条SQL语句,通过JDBC的方式与数据库交互。

二、示例代码

1、定义一个Dao公共类,提供获得数据库连接与释放数据库资源的接口

[java] view plaincopyprint?
  1. package dao; 
  2.  
  3. import java.sql.Connection; 
  4. import java.sql.DriverManager; 
  5. import java.sql.PreparedStatement; 
  6. import java.sql.ResultSet; 
  7. import java.sql.SQLException; 
  8.  
  9. /**
  10. * 提供获取数据库连接、释放资源的接口
  11. */ 
  12. public class JdbcDaoHelper { 
  13.      
  14.     /**
  15.      * 数据库用户名
  16.      */ 
  17.     private staticfinal String USER = "test"
  18.      
  19.     /**
  20.      * 数据库密码
  21.      */ 
  22.     private staticfinal String PASSWORD = "test"
  23.      
  24.     /**
  25.      * 连接数据库的地址
  26.      */ 
  27.     private staticfinal String URL = "jdbc:oracle:thin:@127.0.0.1:1521:study"
  28.      
  29.     private static Connection conn; 
  30.      
  31.     /**
  32.      * 获得一个数据库连接对象
  33.      * @return java.sql.Connection实例
  34.      */ 
  35.     public static Connection getConnection() { 
  36.         try
  37.             if (conn == null) { 
  38.                 Class.forName("oracle.jdbc.OracleDriver"); 
  39.                 conn = DriverManager.getConnection(URL, USER, PASSWORD); 
  40.             } else
  41.                 return conn; 
  42.             } 
  43.         } catch (Exception e) { 
  44.             e.printStackTrace(); 
  45.         } 
  46.         return conn; 
  47.     } 
  48.      
  49.     /**
  50.      * 释放数据库资源
  51.      */ 
  52.     public staticvoid release(PreparedStatement ps,ResultSet rs) { 
  53.         try
  54.             if (conn != null) { 
  55.                 conn.close(); 
  56.                 conn = null
  57.             } 
  58.             if (ps != null) { 
  59.                 ps.close(); 
  60.                 ps = null
  61.             } 
  62.             if (rs != null) { 
  63.                 rs.close(); 
  64.                 rs = null
  65.             } 
  66.         } catch (SQLException e) { 
  67.             e.printStackTrace(); 
  68.         } 
  69.     } 

2、定义一个泛型Dao接口GenericDao<T>

[java] view plaincopyprint?
  1. package dao; 
  2.  
  3. import java.util.List; 
  4. import java.util.Map; 
  5.  
  6. public interface GenericDao<T> { 
  7.      
  8.     public void save(T t)throws Exception; 
  9.      
  10.     public void delete(Object id,Class<T> clazz)throws Exception; 
  11.      
  12.     public void update(T t)throws Exception; 
  13.      
  14.     public T get(Object id,Class<T> clazz)throws Exception; 
  15.      
  16.     /**
  17.      * 根据条件查询
  18.      * @param sqlWhereMap key:条件字段名 value:条件字段值
  19.      * @param clazz
  20.      * @return
  21.      * @throws Exception
  22.      */ 
  23.     public List<T> findAllByConditions(Map<String,Object> sqlWhereMap,Class<T> clazz)throws Exception; 
  24.      

3、定义GenericDao<T>接口JDBC实现类JdbcGenericDaoImpl<T>

[java] view plaincopyprint?
  1. package dao; 
  2.  
  3. import java.beans.IntrospectionException; 
  4. import java.beans.PropertyDescriptor; 
  5. import java.lang.reflect.Field; 
  6. import java.lang.reflect.InvocationTargetException; 
  7. import java.sql.PreparedStatement; 
  8. import java.sql.ResultSet; 
  9. import java.sql.SQLException; 
  10. import java.sql.Timestamp; 
  11. import java.sql.Types; 
  12. import java.util.ArrayList; 
  13. import java.util.Date; 
  14. import java.util.HashMap; 
  15. import java.util.Iterator; 
  16. import java.util.List; 
  17. import java.util.Map; 
  18. import java.util.Set; 
  19. import java.util.Map.Entry; 
  20.  
  21. import annotation.Column; 
  22. import annotation.Entity; 
  23. import annotation.Id; 
  24. import exception.NotFoundAnnotationException; 
  25.  
  26. /**
  27. * 泛型DAO的JDBC实现
  28. * @author 杨信
  29. * @version 1.0
  30. */ 
  31. public class JdbcGenericDaoImpl<T>implements GenericDao<T> { 
  32.      
  33.     //表的别名 
  34.     private staticfinal String TABLE_ALIAS = "t"
  35.  
  36.     @Override 
  37.     public void save(T t)throws Exception { 
  38.         Class<?> clazz = t.getClass(); 
  39.         //获得表名 
  40.         String tableName = getTableName(clazz); 
  41.         //获得字段 
  42.         StringBuilder fieldNames = new StringBuilder();    //字段名 
  43.         List<Object> fieldValues = new ArrayList<Object>();//字段值 
  44.         StringBuilder placeholders = new StringBuilder();  //占位符 
  45.         Field[] fields = clazz.getDeclaredFields(); 
  46.         for (Field field : fields) { 
  47.             PropertyDescriptor pd = new PropertyDescriptor(field.getName(),t.getClass()); 
  48.             if (field.isAnnotationPresent(Id.class)) { 
  49.                 fieldNames.append(field.getAnnotation(Id.class).value()).append(","); 
  50.                 fieldValues.add(pd.getReadMethod().invoke(t)); 
  51.             } else if(field.isAnnotationPresent(Column.class)) { 
  52.                 fieldNames.append(field.getAnnotation(Column.class).value()).append(","); 
  53.                 fieldValues.add(pd.getReadMethod().invoke(t)); 
  54.             } 
  55.             placeholders.append("?").append(","); 
  56.         } 
  57.         //删除最后一个逗号 
  58.         fieldNames.deleteCharAt(fieldNames.length()-1); 
  59.         placeholders.deleteCharAt(placeholders.length()-1); 
  60.          
  61.         //拼接sql 
  62.         StringBuilder sql = new StringBuilder(""); 
  63.         sql.append("insert into ").append(tableName) 
  64.            .append(" (").append(fieldNames.toString()) 
  65.            .append(") values (").append(placeholders).append(")") ; 
  66.         PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql.toString()); 
  67.         //设置SQL参数占位符的值 
  68.         setParameter(fieldValues, ps, false); 
  69.         //执行SQL 
  70.         ps.execute(); 
  71.         JdbcDaoHelper.release(ps, null); 
  72.          
  73.         System.out.println(sql + "\n" + clazz.getSimpleName() +"添加成功!"); 
  74.     } 
  75.  
  76.  
  77.     @Override 
  78.     public void delete(Object id,Class<T> clazz)throws Exception { 
  79.         //获得表名 
  80.         String tableName = getTableName(clazz); 
  81.         //获得ID字段名和值 
  82.         String idFieldName = ""
  83.         boolean flag = false
  84.         Field[] fields = clazz.getDeclaredFields(); 
  85.         for (Field field : fields) { 
  86.             if(field.isAnnotationPresent(Id.class)) { 
  87.                 idFieldName = field.getAnnotation(Id.class).value(); 
  88.                 flag = true
  89.                 break
  90.             } 
  91.         } 
  92.         if (!flag) { 
  93.             throw new NotFoundAnnotationException(clazz.getName() +" object not found id property."); 
  94.         } 
  95.          
  96.         //拼装sql 
  97.         String sql = "delete from " + tableName +" where " + idFieldName + "=?"
  98.         PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql); 
  99.         ps.setObject(1, id); 
  100.         //执行SQL 
  101.         ps.execute(); 
  102.         JdbcDaoHelper.release(ps,null); 
  103.          
  104.         System.out.println(sql + "\n" + clazz.getSimpleName() +"删除成功!"); 
  105.     } 
  106.  
  107.     @Override 
  108.     public void update(T t)throws Exception { 
  109.         Class<?> clazz = t.getClass(); 
  110.         //获得表名 
  111.         String tableName = getTableName(clazz); 
  112.         //获得字段 
  113.         List<Object> fieldNames = new ArrayList<Object>(); //字段名 
  114.         List<Object> fieldValues = new ArrayList<Object>();//字段值 
  115.         List<String> placeholders = new ArrayList<String>();//占位符 
  116.         String idFieldName = ""
  117.         Object idFieldValue = ""
  118.         Field[] fields = clazz.getDeclaredFields(); 
  119.         for (Field field : fields) { 
  120.             PropertyDescriptor pd = new PropertyDescriptor(field.getName(),t.getClass()); 
  121.             if (field.isAnnotationPresent(Id.class)) { 
  122.                 idFieldName = field.getAnnotation(Id.class).value(); 
  123.                 idFieldValue = pd.getReadMethod().invoke(t); 
  124.             } else if(field.isAnnotationPresent(Column.class)) { 
  125.                 fieldNames.add(field.getAnnotation(Column.class).value()); 
  126.                 fieldValues.add(pd.getReadMethod().invoke(t)); 
  127.                 placeholders.add("?"); 
  128.             } 
  129.         } 
  130.         //ID作为更新条件,放在集合中的最后一个元素 
  131.         fieldNames.add(idFieldName); 
  132.         fieldValues.add(idFieldValue); 
  133.         placeholders.add("?"); 
  134.          
  135.         //拼接sql 
  136.         StringBuilder sql = new StringBuilder(""); 
  137.         sql.append("update ").append(tableName).append(" set "); 
  138.         int index = fieldNames.size() -1
  139.         for (int i =0; i < index; i++) { 
  140.             sql.append(fieldNames.get(i)).append("=").append(placeholders.get(i)).append(","); 
  141.         } 
  142.         sql.deleteCharAt(sql.length()-1).append(" where ").append(fieldNames.get(index)).append("=").append("?"); 
  143.          
  144.         //设置SQL参数占位符的值 
  145.         PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql.toString()); 
  146.         setParameter(fieldValues, ps, false); 
  147.          
  148.         //执行SQL 
  149.         ps.execute(); 
  150.         JdbcDaoHelper.release(ps, null); 
  151.          
  152.         System.out.println(sql + "\n" + clazz.getSimpleName() +"修改成功."); 
  153.     } 
  154.  
  155.     @Override 
  156.     public T get(Object id,Class<T> clazz)throws Exception { 
  157.         String idFieldName = ""
  158.         Field[] fields = clazz.getDeclaredFields(); 
  159.         boolean flag = false
  160.         for (Field field : fields) { 
  161.             if (field.isAnnotationPresent(Id.class)) { 
  162.                 idFieldName = field.getAnnotation(Id.class).value(); 
  163.                 flag = true
  164.                 break
  165.             }  
  166.         } 
  167.          
  168.         if (!flag) { 
  169.             throw new NotFoundAnnotationException(clazz.getName() +" object not found id property."); 
  170.         } 
  171.          
  172.         //拼装SQL 
  173.         Map<String,Object> sqlWhereMap = new HashMap<String, Object>(); 
  174.         sqlWhereMap.put(TABLE_ALIAS + "." + idFieldName, id); 
  175.          
  176.         List<T> list = findAllByConditions(sqlWhereMap, clazz); 
  177.         return list.size() >0 ? list.get(0) :null
  178.     } 
  179.  
  180.     @Override 
  181.     public List<T> findAllByConditions(Map<String,Object> sqlWhereMap,Class<T> clazz)throws Exception { 
  182.         List<T> list = new ArrayList<T>(); 
  183.         String tableName = getTableName(clazz); 
  184.         String idFieldName = ""
  185.         //存储所有字段的信息 
  186.         //通过反射获得要查询的字段 
  187.         StringBuffer fieldNames = new StringBuffer(); 
  188.         Field[] fields = clazz.getDeclaredFields(); 
  189.         for (Field field : fields) { 
  190.             String propertyName = field.getName(); 
  191.             if (field.isAnnotationPresent(Id.class)) { 
  192.                 idFieldName = field.getAnnotation(Id.class).value(); 
  193.                 fieldNames.append(TABLE_ALIAS + "." + idFieldName) 
  194.                           .append(" as ").append(propertyName).append(","); 
  195.             } else if (field.isAnnotationPresent(Column.class)) { 
  196.                 fieldNames.append(TABLE_ALIAS + "." + field.getAnnotation(Column.class).value()) 
  197.                           .append(" as ").append(propertyName).append(","); 
  198.             } 
  199.         } 
  200.         fieldNames.deleteCharAt(fieldNames.length()-1); 
  201.          
  202.         //拼装SQL 
  203.         String sql = "select " + fieldNames +" from " + tableName + " " + TABLE_ALIAS; 
  204.         PreparedStatement ps = null
  205.         List<Object> values = null
  206.         if (sqlWhereMap != null) { 
  207.             List<Object> sqlWhereWithValues = getSqlWhereWithValues(sqlWhereMap); 
  208.             if (sqlWhereWithValues !=null) { 
  209.                 //拼接SQL条件 
  210.                 String sqlWhere = (String)sqlWhereWithValues.get(0); 
  211.                 sql += sqlWhere; 
  212.                 //得到SQL条件中占位符的值 
  213.                 values = (List<Object>) sqlWhereWithValues.get(1); 
  214.             } 
  215.         }  
  216.          
  217.         //设置参数占位符的值 
  218.         if (values != null) { 
  219.             ps = JdbcDaoHelper.getConnection().prepareStatement(sql); 
  220.             setParameter(values, ps, true); 
  221.         } else
  222.             ps = JdbcDaoHelper.getConnection().prepareStatement(sql); 
  223.         } 
  224.          
  225.          
  226.         //执行SQL 
  227.         ResultSet rs = ps.executeQuery(); 
  228.         while(rs.next()) { 
  229.             T t = clazz.newInstance(); 
  230.             initObject(t, fields, rs); 
  231.             list.add(t); 
  232.         } 
  233.          
  234.         //释放资源 
  235.         JdbcDaoHelper.release(ps, rs); 
  236.          
  237.         System.out.println(sql); 
  238.         return list; 
  239.     } 
  240.      
  241.     /**
  242.      * 根据结果集初始化对象
  243.      */ 
  244.     private void initObject(T t, Field[] fields, ResultSet rs) 
  245.             throws SQLException, IntrospectionException, 
  246.             IllegalAccessException, InvocationTargetException { 
  247.         for (Field field : fields) { 
  248.             String propertyName = field.getName(); 
  249.             Object paramVal = null
  250.             Class<?> clazzField = field.getType(); 
  251.             if (clazzField == String.class) { 
  252.                 paramVal = rs.getString(propertyName); 
  253.             } else if (clazzField == short.class || clazzField == Short.class) { 
  254.                 paramVal = rs.getShort(propertyName); 
  255.             } else if (clazzField == int.class || clazzField == Integer.class) { 
  256.                 paramVal = rs.getInt(propertyName); 
  257.             } else if (clazzField == long.class || clazzField == Long.class) { 
  258.                 paramVal = rs.getLong(propertyName); 
  259.             } else if (clazzField == float.class || clazzField == Float.class) { 
  260.                 paramVal = rs.getFloat(propertyName); 
  261.             } else if (clazzField == double.class || clazzField == Double.class) { 
  262.                 paramVal = rs.getDouble(propertyName); 
  263.             } else if (clazzField == boolean.class || clazzField == Boolean.class) { 
  264.                 paramVal = rs.getBoolean(propertyName); 
  265.             } else if (clazzField == byte.class || clazzField == Byte.class) { 
  266.                 paramVal = rs.getByte(propertyName); 
  267.             } else if (clazzField == char.class || clazzField == Character.class) { 
  268.                 paramVal = rs.getCharacterStream(propertyName); 
  269.             } else if (clazzField == Date.class) { 
  270.                 paramVal = rs.getTimestamp(propertyName); 
  271.             } else if (clazzField.isArray()) { 
  272.                 paramVal = rs.getString(propertyName).split(",");  //以逗号分隔的字符串 
  273.             }  
  274.             PropertyDescriptor pd = new PropertyDescriptor(propertyName,t.getClass()); 
  275.             pd.getWriteMethod().invoke(t, paramVal); 
  276.         } 
  277.     } 
  278.      
  279.     /**
  280.      * 根据条件,返回sql条件和条件中占位符的值
  281.      * @param sqlWhereMap key:字段名 value:字段值
  282.      * @return 第一个元素为SQL条件,第二个元素为SQL条件中占位符的值
  283.      */ 
  284.     private List<Object> getSqlWhereWithValues(Map<String,Object> sqlWhereMap) { 
  285.         if (sqlWhereMap.size() <1 )return null
  286.         List<Object> list = new ArrayList<Object>(); 
  287.         List<Object> fieldValues = new ArrayList<Object>(); 
  288.         StringBuffer sqlWhere = new StringBuffer(" where "); 
  289.         Set<Entry<String, Object>> entrySets = sqlWhereMap.entrySet(); 
  290.         for (Iterator<Entry<String, Object>> iteraotr = entrySets.iterator();iteraotr.hasNext();) { 
  291.             Entry<String, Object> entrySet = iteraotr.next(); 
  292.             fieldValues.add(entrySet.getValue()); 
  293.             Object value = entrySet.getValue(); 
  294.             if (value.getClass() == String.class) { 
  295.                 sqlWhere.append(entrySet.getKey()).append(" like ").append("?").append(" and "); 
  296.             } else
  297.                 sqlWhere.append(entrySet.getKey()).append("=").append("?").append(" and "); 
  298.             } 
  299.         } 
  300.         sqlWhere.delete(sqlWhere.lastIndexOf("and"), sqlWhere.length()); 
  301.         list.add(sqlWhere.toString()); 
  302.         list.add(fieldValues); 
  303.         return list; 
  304.     } 
  305.      
  306.      
  307.     /**
  308.      * 获得表名
  309.      */ 
  310.     private String getTableName(Class<?> clazz)throws NotFoundAnnotationException { 
  311.         if (clazz.isAnnotationPresent(Entity.class)) { 
  312.             Entity entity = clazz.getAnnotation(Entity.class); 
  313.             return entity.value(); 
  314.         } else
  315.             throw new NotFoundAnnotationException(clazz.getName() +" is not Entity Annotation."); 
  316.         } 
  317.     } 
  318.      
  319.     /**
  320.      * 设置SQL参数占位符的值
  321.      */ 
  322.     private void setParameter(List<Object> values, PreparedStatement ps,boolean isSearch) 
  323.             throws SQLException { 
  324.         for (int i =1; i <= values.size(); i++) { 
  325.             Object fieldValue = values.get(i-1); 
  326.             Class<?> clazzValue = fieldValue.getClass(); 
  327.             if (clazzValue == String.class) { 
  328.                 if (isSearch)  
  329.                     ps.setString(i, "%" + (String)fieldValue +"%"); 
  330.                 else 
  331.                     ps.setString(i,(String)fieldValue); 
  332.                      
  333.             } else if (clazzValue == boolean.class || clazzValue == Boolean.class) { 
  334.                 ps.setBoolean(i, (Boolean)fieldValue); 
  335.             } else if (clazzValue == byte.class || clazzValue == Byte.class) { 
  336.                 ps.setByte(i, (Byte)fieldValue); 
  337.             } else if (clazzValue == char.class || clazzValue == Character.class) { 
  338.                 ps.setObject(i, fieldValue,Types.CHAR); 
  339.             } else if (clazzValue == Date.class) { 
  340.                 ps.setTimestamp(i, new Timestamp(((Date) fieldValue).getTime())); 
  341.             } else if (clazzValue.isArray()) { 
  342.                 Object[] arrayValue = (Object[]) fieldValue; 
  343.                 StringBuffer sb = new StringBuffer(); 
  344.                 for (int j =0; j < arrayValue.length; j++) { 
  345.                     sb.append(arrayValue[j]).append("、"); 
  346.                 } 
  347.                 ps.setString(i, sb.deleteCharAt(sb.length()-1).toString()); 
  348.             } else
  349.                 ps.setObject(i, fieldValue, Types.NUMERIC); 
  350.             } 
  351.         } 
  352.     } 


 

4、定义三个注解Entity、Id、Column,生命周期保存在运行期间,以便通过反射获取

1)、Entity

 

[java] view plaincopyprint?
  1. package annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Retention; 
  5. import java.lang.annotation.RetentionPolicy; 
  6. import java.lang.annotation.Target; 
  7.  
  8. /**
  9. * 数据库表的的名称
  10. */ 
  11. @Retention(RetentionPolicy.RUNTIME) 
  12. @Target(ElementType.TYPE) 
  13. public @interface Entity { 
  14.  
  15.     /**
  16.      * 表名
  17.      */ 
  18.     String value(); 
  19.      
2)、Id
[java] view plaincopyprint?
  1. package annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Retention; 
  5. import java.lang.annotation.RetentionPolicy; 
  6. import java.lang.annotation.Target; 
  7.  
  8. /**
  9. * 标识数据库字段的ID
  10. */ 
  11. @Retention(RetentionPolicy.RUNTIME) 
  12. @Target(ElementType.FIELD) 
  13. public @interface Id { 
  14.  
  15.     /**
  16.      * ID的名称
  17.      * @return
  18.      */ 
  19.     String value(); 
  20.      
3)、Column
[java] view plaincopyprint?
  1. package annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Retention; 
  5. import java.lang.annotation.RetentionPolicy; 
  6. import java.lang.annotation.Target; 
  7.  
  8. /**
  9. * 标识数据库字段的名称
  10. * @author 杨信
  11. *
  12. */ 
  13. @Retention(RetentionPolicy.RUNTIME) 
  14. @Target(ElementType.FIELD) 
  15. public @interface Column { 
  16.      
  17.     /**
  18.      * 字段名称
  19.      */ 
  20.     String value(); 
  21.      
  22.     /**
  23.      * 字段的类型
  24.      * @return
  25.      */ 
  26.     Class<?> type() default String.class
  27.      
  28.     /**
  29.      * 字段的长度
  30.      * @return
  31.      */ 
  32.     int length() default0
  33.  


五、定义一个JavaBean,用于测试使用

要求:

1)、类名必须用Entity注解标识,并指定数据库中对应的表名

2)、Id属性必须用Id注解标识,并指定表中所对应的字段名

3)、其它属性必须用Column注解标识,并指定表中所对应的字段名

4)、JavaBean属性的数据类型目前只实现了8大基本数据类型、String和这些基本类型的数组类型

5)、JavaBean属性目前没有做字段的长度与类型的判断,待以后改进。

[java] view plaincopyprint?
  1. package model; 
  2.  
  3. import java.util.Date; 
  4.  
  5. import annotation.Column; 
  6. import annotation.Entity; 
  7. import annotation.Id; 
  8.  
  9. /**
  10. * 图书
  11. */ 
  12. @Entity("t_book")  //表名 
  13. public class Book { 
  14.  
  15.     /**
  16.      * 图书编号
  17.      */ 
  18.     @Id("t_isbn"
  19.     private String isbn; 
  20.  
  21.     /**
  22.      * 书名
  23.      */ 
  24.     @Column("t_name"
  25.     private String name; 
  26.  
  27.     /**
  28.      * 作者
  29.      */ 
  30.     @Column("t_author"
  31.     private String author; 
  32.  
  33.     /**
  34.      * 出版社
  35.      */ 
  36.     @Column("t_publishing"
  37.     private String publishing; 
  38.  
  39.     /**
  40.      * 出版时间
  41.      */ 
  42.     @Column(value = "t_pubdate"
  43.     private Date pubdate; 
  44.  
  45.     /**
  46.      * 价格
  47.      */ 
  48.     @Column(value = "t_price"
  49.     private double price; 
  50.  
  51.     public String getIsbn() { 
  52.         return isbn; 
  53.     } 
  54.  
  55.     public void setIsbn(String isbn) { 
  56.         this.isbn = isbn; 
  57.     } 
  58.  
  59.     public String getName() { 
  60.         return name; 
  61.     } 
  62.  
  63.     public void setName(String name) { 
  64.         this.name = name; 
  65.     } 
  66.  
  67.     public String getAuthor() { 
  68.         return author; 
  69.     } 
  70.  
  71.     public void setAuthor(String author) { 
  72.         this.author = author; 
  73.     } 
  74.  
  75.     public String getPublishing() { 
  76.         return publishing; 
  77.     } 
  78.  
  79.     public void setPublishing(String publishing) { 
  80.         this.publishing = publishing; 
  81.     } 
  82.  
  83.     public Date getPubdate() { 
  84.         return pubdate; 
  85.     } 
  86.  
  87.     public void setPubdate(Date pubdate) { 
  88.         this.pubdate = pubdate; 
  89.     } 
  90.  
  91.     public double getPrice() { 
  92.         return price; 
  93.     } 
  94.  
  95.     public void setPrice(double price) { 
  96.         this.price = price; 
  97.     } 
  98.  
  99.     @Override 
  100.     public String toString() { 
  101.         return "书名: " + name +" 图书编号: " + isbn + " 作者: " + author 
  102.                 + " 出版社: " + publishing +" 出版时间: " + pubdate 
  103.                 + " 价格: " + price; 
  104.     } 


六、使用Junit4进行单元测试

[java] view plaincopyprint?
  1. package xml; 
  2.  
  3. import java.io.InputStream; 
  4. import java.util.HashMap; 
  5. import java.util.List; 
  6. import java.util.Map; 
  7.  
  8. import model.Book; 
  9.  
  10. import org.junit.BeforeClass; 
  11. import org.junit.Test; 
  12.  
  13. import util.DateUtils; 
  14. import dao.GenericDao; 
  15. import dao.JdbcGenericDaoImpl; 
  16.  
  17. /**
  18. * 测试泛型DAO的CRUD操作
  19. */ 
  20. public class GenericDaoTest { 
  21.      
  22.     private GenericDao<Book> bookDao =new JdbcGenericDaoImpl<Book>(); 
  23.      
  24.     private static InputStream is; 
  25.  
  26.     @BeforeClass 
  27.     public staticvoid setUpBeforeClass() throws Exception { 
  28.         is = XmlParserTest.class.getResourceAsStream("/books.xml"); 
  29.     } 
  30.      
  31.     @Test 
  32.     public void testSave()throws Exception { 
  33.         List<Book> books = SaxHelper.saxReader(is); 
  34.         for (Book book : books) { 
  35.             bookDao.save(book); 
  36.         } 
  37.     } 
  38.      
  39.     @Test 
  40.     public void testStudentFindAll1()throws Exception { 
  41.         System.out.println("\n-------------更新、删除前,测试查询所有记录--------------------"); 
  42.         List<Book> books = bookDao.findAllByConditions(null, Book.class); 
  43.         for (Book book : books) { 
  44.             System.out.println(book); 
  45.         } 
  46.     }  
  47.      
  48.     @Test 
  49.     public void testDelete()throws Exception { 
  50.         System.out.println("\n-------------测试删除一条记录--------------------"); 
  51.         bookDao.delete("9787111349662",Book.class); 
  52.     } 
  53.      
  54.     @Test 
  55.     public void testGet()throws Exception { 
  56.         System.out.println("\n-------------测试查询一条记录--------------------"); 
  57.         Book book = bookDao.get("9787121025389", Book.class); 
  58.         System.out.println(book); 
  59.     } 
  60.      
  61.     @Test 
  62.     public void testUpdate()throws Exception { 
  63.         System.out.println("\n-------------测试修改一条记录--------------------"); 
  64.         Book book = new Book(); 
  65.         book.setIsbn("9787121025389"); 
  66.         book.setName("JAVA面向对象编程"); 
  67.         book.setAuthor("孙卫琴"); 
  68.         book.setPublishing("电子工业出版社"); 
  69.         book.setPubdate(DateUtils.string2Date("yyyy-MM-dd","2006-07-01")); 
  70.         book.setPrice(50.6); 
  71.         bookDao.update(book); 
  72.     } 
  73.      
  74.     @Test 
  75.     public void testStudentFindAll2()throws Exception { 
  76.         System.out.println("\n-------------更新、删除前,测试根据条件查询所有记录--------------------"); 
  77.         Map<String,Object> sqlWhereMap = new HashMap<String, Object>(); 
  78.         //sqlWhereMap.put("t_isbn", "9787111213826"); 
  79.         //sqlWhereMap.put("t_name", "Java"); 
  80.         sqlWhereMap.put("t_publishing","机械工业出版社"); 
  81.         //sqlWhereMap.put("t_pubdate", new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2007-01-01 12:06:00").getTime())); 
  82.         List<Book> books = bookDao.findAllByConditions(null, Book.class); 
  83.         for (Book book : books) { 
  84.             System.out.println(book); 
  85.         } 
  86.     }  
  87.  
七、测试结果

 

 

原创粉丝点击