基于SpringJdbc的泛型Dao

转载自:http://1194867672-qq-com.iteye.com/blog/1455814

使用的Spring是3.1版本,不是3.0版本。两者还是有区别的,其中一点就是:SimpleJdbcTemplate在3.1版本被标记为过时了,而SimpleJdbcTemplate的一些方法,被JdbcTemplate吸收了。所以,个人推荐使用3.1版本.

 

 

需要的JAR文件:

 

org.springframework.aop-3.1.0.RELEASE.jar

org.springframework.asm-3.1.0.RELEASE.jar

org.springframework.beans-3.1.0.RELEASE.jar

org.springframework.context-3.1.0.RELEASE.jar

org.springframework.core-3.1.0.RELEASE.jar

org.springframework.expression-3.1.0.RELEASE.jar

org.springframework.jdbc-3.1.0.RELEASE.jar

org.springframework.test-3.1.0.RELEASE.jar

org.springframework.transaction-3.1.0.RELEASE.jar

 

com.springsource.net.sf.cglib-2.2.0.jar

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

com.springsource.org.apache.commons.logging-1.1.1.jar

com.springsource.org.junit-4.7.0.jar

 

ojdbc14.jar

 

数据库脚本:

Sql代码   收藏代码
  1. --创建商品表  
  2. create table product(  
  3.     id      varchar2(255)   primary key,  
  4.     name        varchar2(255),  
  5.     author          varchar2(255),  
  6.     price       number(6,2),  
  7.     quantity    number,  
  8.     description varchar2(255)  
  9. );  

 

 

实体类:

Java代码   收藏代码
  1. package org.chendl.springjdbc.domain;  
  2.   
  3.   
  4. public class Product /*implements Serializable*///暂不序列化  
  5.   
  6.     private String id;  
  7.     private String name;  
  8.     private String author;  
  9.     private double price;  
  10.     private int quantity;  
  11.     private String description;  
  12.   
  13.     public Product() {  
  14.   
  15.     }  
  16.   
  17.     // getter and setter  
  18.   
  19.     @Override  
  20.     public String toString() {  
  21.         return "Product [id=" + id + ", name=" + name + ", author=" + author + ", price=" + price + ", quantity="  
  22.                 + quantity + ", description=" + description + "]\n";  
  23.     }  
  24. }  

 

 

正题:

 

BaseDao接口不提供了,附件中会有,直接给出BaseDaoImpl

 

Java代码   收藏代码
  1. package org.chendl.springjdbc.dao.impl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.ParameterizedType;  
  6. import java.sql.Types;  
  7. import java.util.LinkedHashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. import org.chendl.springjdbc.dao.BaseDao;  
  12. import org.chendl.springjdbc.util.QueryResult;  
  13. import org.springframework.jdbc.core.BeanPropertyRowMapper;  
  14. import org.springframework.jdbc.core.JdbcTemplate;  
  15. import org.springframework.jdbc.core.RowMapper;  
  16.   
  17. /** 
  18.  * 使用场景 
  19.  *  
  20.  * 数据库是Oracle 
  21.  * 主键列名为id 
  22.  * 主键由程序提供(这里用的是UUID) 
  23.  * 实体类名和数据库表名一致  比如:类名Product 表名product、PRODUCT、Produc 都可以 t_product 不可以 
  24.  */  
  25. public class BaseDaoImpl<T> implements BaseDao<T> {  
  26.   
  27.     /** 设置一些操作的常量 */  
  28.     public static final String SQL_INSERT = "insert";  
  29.     public static final String SQL_UPDATE = "update";  
  30.     public static final String SQL_DELETE = "delete";  
  31.   
  32.     private JdbcTemplate jdbcTemplate;  
  33.   
  34.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  35.         this.jdbcTemplate = jdbcTemplate;  
  36.     }  
  37.   
  38.     private Class<T> entityClass;  
  39.   
  40.     @SuppressWarnings("unchecked")  
  41.     public BaseDaoImpl() {  
  42.         ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();  
  43.         entityClass = (Class<T>) type.getActualTypeArguments()[0];  
  44.         System.out.println("Dao实现类是:" + entityClass.getName());  
  45.     }  
  46.   
  47.     @Override  
  48.     public void save(T entity) {  
  49.         String sql = this.makeSql(SQL_INSERT);  
  50.         Object[] args = this.setArgs(entity, SQL_INSERT);  
  51.         int[] argTypes = this.setArgTypes(entity, SQL_INSERT);  
  52.         jdbcTemplate.update(sql.toString(), args, argTypes);  
  53.     }  
  54.   
  55.     @Override  
  56.     public void update(T entity) {  
  57.         String sql = this.makeSql(SQL_UPDATE);  
  58.         Object[] args = this.setArgs(entity, SQL_UPDATE);  
  59.         int[] argTypes = this.setArgTypes(entity, SQL_UPDATE);  
  60.         jdbcTemplate.update(sql, args, argTypes);  
  61.     }  
  62.   
  63.     @Override  
  64.     public void delete(T entity) {  
  65.         String sql = this.makeSql(SQL_DELETE);  
  66.         Object[] args = this.setArgs(entity, SQL_DELETE);  
  67.         int[] argTypes = this.setArgTypes(entity, SQL_DELETE);  
  68.         jdbcTemplate.update(sql, args, argTypes);  
  69.     }  
  70.   
  71.     @Override  
  72.     public void delete(Serializable id) {  
  73.         String sql = " DELETE FROM " + entityClass.getSimpleName() + " WHERE id=?";  
  74.         jdbcTemplate.update(sql, id);  
  75.     }  
  76.   
  77.     @Override  
  78.     public void deleteAll() {  
  79.         String sql = " TRUNCATE TABLE " + entityClass.getSimpleName();  
  80.         jdbcTemplate.execute(sql);  
  81.     }  
  82.   
  83.     /** 
  84.      * 未完成 
  85.      */  
  86.     @Override  
  87.     public void batchSave(List<T> list) {  
  88.   
  89.     }  
  90.   
  91.     /** 
  92.      * 未完成 
  93.      */  
  94.     @Override  
  95.     public void batchUpdate(List<T> list) {  
  96.   
  97.     }  
  98.   
  99.     /** 
  100.      * 未完成 
  101.      */  
  102.     @Override  
  103.     public void batchDelete(List<T> list) {  
  104.   
  105.     }  
  106.   
  107.     @Override  
  108.     public T findById(Serializable id) {  
  109.         String sql = "SELECT * FROM " + entityClass.getSimpleName() + " WHERE id=?";  
  110.         RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);  
  111.         return jdbcTemplate.query(sql, rowMapper, id).get(0);  
  112.     }  
  113.   
  114.     @Override  
  115.     public List<T> findAll() {  
  116.         String sql = "SELECT * FROM " + entityClass.getSimpleName();  
  117.         RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);  
  118.         return jdbcTemplate.query(sql, rowMapper);  
  119.     }  
  120.   
  121.     @Override  
  122.     public QueryResult<T> findByPage(int pageNo, int pageSize) {  
  123.         List<T> list = this.find(pageNo, pageSize, nullnull);  
  124.         int totalRow = this.count(null);  
  125.         return new QueryResult<T>(list, totalRow);  
  126.     }  
  127.   
  128.     @Override  
  129.     public QueryResult<T> findByPage(int pageNo, int pageSize, Map<String, String> where) {  
  130.         List<T> list = this.find(pageNo, pageSize, where, null);  
  131.         int totalRow = this.count(where);  
  132.         return new QueryResult<T>(list, totalRow);  
  133.     }  
  134.   
  135.     @Override  
  136.     public QueryResult<T> findByPage(int pageNo, int pageSize, LinkedHashMap<String, String> orderby) {  
  137.         List<T> list = this.find(pageNo, pageSize, null, orderby);  
  138.         int totalRow = this.count(null);  
  139.         return new QueryResult<T>(list, totalRow);  
  140.     }  
  141.   
  142.     @Override  
  143.     public QueryResult<T> findByPage(int pageNo, int pageSize, Map<String, String> where,  
  144.             LinkedHashMap<String, String> orderby) {  
  145.         List<T> list = this.find(pageNo, pageSize, where, orderby);  
  146.         int totalRow = this.count(where);  
  147.         return new QueryResult<T>(list, totalRow);  
  148.     }  
  149.   
  150.     // 组装SQL  
  151.     private String makeSql(String sqlFlag) {  
  152.         StringBuffer sql = new StringBuffer();  
  153.         Field[] fields = entityClass.getDeclaredFields();  
  154.         if (sqlFlag.equals(SQL_INSERT)) {  
  155.             sql.append(" INSERT INTO " + entityClass.getSimpleName());  
  156.             sql.append("(");  
  157.             for (int i = 0; fields != null && i < fields.length; i++) {  
  158.                 fields[i].setAccessible(true); // 暴力反射  
  159.                 String column = fields[i].getName();  
  160.                 sql.append(column).append(",");  
  161.             }  
  162.             sql = sql.deleteCharAt(sql.length() - 1);  
  163.             sql.append(") VALUES (");  
  164.             for (int i = 0; fields != null && i < fields.length; i++) {  
  165.                 sql.append("?,");  
  166.             }  
  167.             sql = sql.deleteCharAt(sql.length() - 1);  
  168.             sql.append(")");  
  169.         } else if (sqlFlag.equals(SQL_UPDATE)) {  
  170.             sql.append(" UPDATE " + entityClass.getSimpleName() + " SET ");  
  171.             for (int i = 0; fields != null && i < fields.length; i++) {  
  172.                 fields[i].setAccessible(true); // 暴力反射  
  173.                 String column = fields[i].getName();  
  174.                 if (column.equals("id")) { // id 代表主键  
  175.                     continue;  
  176.                 }  
  177.                 sql.append(column).append("=").append("?,");  
  178.             }  
  179.             sql = sql.deleteCharAt(sql.length() - 1);  
  180.             sql.append(" WHERE id=?");  
  181.         } else if (sqlFlag.equals(SQL_DELETE)) {  
  182.             sql.append(" DELETE FROM " + entityClass.getSimpleName() + " WHERE id=?");  
  183.         }  
  184.         System.out.println("SQL=" + sql);  
  185.         return sql.toString();  
  186.   
  187.     }  
  188.   
  189.     // 设置参数  
  190.     private Object[] setArgs(T entity, String sqlFlag) {  
  191.         Field[] fields = entityClass.getDeclaredFields();  
  192.         if (sqlFlag.equals(SQL_INSERT)) {  
  193.             Object[] args = new Object[fields.length];  
  194.             for (int i = 0; args != null && i < args.length; i++) {  
  195.                 try {  
  196.                     fields[i].setAccessible(true); // 暴力反射  
  197.                     args[i] = fields[i].get(entity);  
  198.                 } catch (Exception e) {  
  199.                     e.printStackTrace();  
  200.                 }  
  201.             }  
  202.             return args;  
  203.         } else if (sqlFlag.equals(SQL_UPDATE)) {  
  204.             Object[] tempArr = new Object[fields.length];  
  205.             for (int i = 0; tempArr != null && i < tempArr.length; i++) {  
  206.                 try {  
  207.                     fields[i].setAccessible(true); // 暴力反射  
  208.                     tempArr[i] = fields[i].get(entity);  
  209.                 } catch (Exception e) {  
  210.                     e.printStackTrace();  
  211.                 }  
  212.             }  
  213.             Object[] args = new Object[fields.length];  
  214.             System.arraycopy(tempArr, 1, args, 0, tempArr.length - 1); // 数组拷贝  
  215.             args[args.length - 1] = tempArr[0];  
  216.             return args;  
  217.         } else if (sqlFlag.equals(SQL_DELETE)) {  
  218.             Object[] args = new Object[1]; // 长度是1  
  219.             fields[0].setAccessible(true); // 暴力反射  
  220.             try {  
  221.                 args[0] = fields[0].get(entity);  
  222.             } catch (Exception e) {  
  223.                 e.printStackTrace();  
  224.             }  
  225.             return args;  
  226.         }  
  227.         return null;  
  228.   
  229.     }  
  230.   
  231.     // 设置参数类型(写的不全,只是一些常用的)  
  232.     private int[] setArgTypes(T entity, String sqlFlag) {  
  233.         Field[] fields = entityClass.getDeclaredFields();  
  234.         if (sqlFlag.equals(SQL_INSERT)) {  
  235.             int[] argTypes = new int[fields.length];  
  236.             try {  
  237.                 for (int i = 0; argTypes != null && i < argTypes.length; i++) {  
  238.                     fields[i].setAccessible(true); // 暴力反射  
  239.                     if (fields[i].get(entity).getClass().getName().equals("java.lang.String")) {  
  240.                         argTypes[i] = Types.VARCHAR;  
  241.                     } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Double")) {  
  242.                         argTypes[i] = Types.DECIMAL;  
  243.                     } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Integer")) {  
  244.                         argTypes[i] = Types.INTEGER;  
  245.                     } else if (fields[i].get(entity).getClass().getName().equals("java.util.Date")) {  
  246.                         argTypes[i] = Types.DATE;  
  247.                     }  
  248.                 }  
  249.             } catch (Exception e) {  
  250.                 e.printStackTrace();  
  251.             }  
  252.             return argTypes;  
  253.         } else if (sqlFlag.equals(SQL_UPDATE)) {  
  254.             int[] tempArgTypes = new int[fields.length];  
  255.             int[] argTypes = new int[fields.length];  
  256.             try {  
  257.                 for (int i = 0; tempArgTypes != null && i < tempArgTypes.length; i++) {  
  258.                     fields[i].setAccessible(true); // 暴力反射  
  259.                     if (fields[i].get(entity).getClass().getName().equals("java.lang.String")) {  
  260.                         tempArgTypes[i] = Types.VARCHAR;  
  261.                     } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Double")) {  
  262.                         tempArgTypes[i] = Types.DECIMAL;  
  263.                     } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Integer")) {  
  264.                         tempArgTypes[i] = Types.INTEGER;  
  265.                     } else if (fields[i].get(entity).getClass().getName().equals("java.util.Date")) {  
  266.                         tempArgTypes[i] = Types.DATE;  
  267.                     }  
  268.                 }  
  269.                 System.arraycopy(tempArgTypes, 1, argTypes, 0, tempArgTypes.length - 1); // 数组拷贝  
  270.                 argTypes[argTypes.length - 1] = tempArgTypes[0];  
  271.   
  272.             } catch (Exception e) {  
  273.                 e.printStackTrace();  
  274.             }  
  275.             return argTypes;  
  276.   
  277.         } else if (sqlFlag.equals(SQL_DELETE)) {  
  278.             int[] argTypes = new int[1]; // 长度是1  
  279.             try {  
  280.                 fields[0].setAccessible(true); // 暴力反射  
  281.                 if (fields[0].get(entity).getClass().getName().equals("java.lang.String")) {  
  282.                     argTypes[0] = Types.VARCHAR;  
  283.                 } else if (fields[0].get(entity).getClass().getName().equals("java.lang.Integer")) {  
  284.                     argTypes[0] = Types.INTEGER;  
  285.                 }  
  286.   
  287.             } catch (Exception e) {  
  288.                 e.printStackTrace();  
  289.             }  
  290.             return argTypes;  
  291.         }  
  292.         return null;  
  293.     }  
  294.   
  295.     private List<T> find(int pageNo, int pageSize, Map<String, String> where, LinkedHashMap<String, String> orderby) {  
  296.         // where 与 order by 要写在select * from table 的后面,而不是where rownum<=? ) where rn>=?的后面  
  297.         StringBuffer sql = new StringBuffer(" SELECT * FROM (SELECT t.*,ROWNUM rn FROM (SELECT * FROM "  
  298.                 + entityClass.getSimpleName());  
  299.         if (where != null && where.size() > 0) {  
  300.             sql.append(" WHERE "); // 注意不是where  
  301.             for (Map.Entry<String, String> me : where.entrySet()) {  
  302.                 String columnName = me.getKey();  
  303.                 String columnValue = me.getValue();  
  304.                 sql.append(columnName).append(" ").append(columnValue).append(" AND "); // 没有考虑or的情况  
  305.             }  
  306.             int endIndex = sql.lastIndexOf("AND");  
  307.             if (endIndex > 0) {  
  308.                 sql = new StringBuffer(sql.substring(0, endIndex));  
  309.             }  
  310.         }  
  311.         if (orderby != null && orderby.size() > 0) {  
  312.             sql.append(" ORDER BY ");  
  313.             for (Map.Entry<String, String> me : orderby.entrySet()) {  
  314.                 String columnName = me.getKey();  
  315.                 String columnValue = me.getValue();  
  316.                 sql.append(columnName).append(" ").append(columnValue).append(",");  
  317.             }  
  318.             sql = sql.deleteCharAt(sql.length() - 1);  
  319.         }  
  320.         sql.append(" ) t WHERE ROWNUM<=? ) WHERE rn>=? ");  
  321.         System.out.println("SQL=" + sql);  
  322.         Object[] args = { pageNo * pageSize, (pageNo - 1) * pageSize + 1 };  
  323.         RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);  
  324.         return jdbcTemplate.query(sql.toString(), args, rowMapper);  
  325.     }  
  326.   
  327.     private int count(Map<String, String> where) {  
  328.         StringBuffer sql = new StringBuffer(" SELECT COUNT(*) FROM " + entityClass.getSimpleName());  
  329.         if (where != null && where.size() > 0) {  
  330.             sql.append(" WHERE ");  
  331.             for (Map.Entry<String, String> me : where.entrySet()) {  
  332.                 String columnName = me.getKey();  
  333.                 String columnValue = me.getValue();  
  334.                 sql.append(columnName).append(" ").append(columnValue).append(" AND "); // 没有考虑or的情况  
  335.             }  
  336.             int endIndex = sql.lastIndexOf("AND");  
  337.             if (endIndex > 0) {  
  338.                 sql = new StringBuffer(sql.substring(0, endIndex));  
  339.             }  
  340.         }  
  341.         System.out.println("SQL=" + sql);  
  342.         return jdbcTemplate.queryForInt(sql.toString());  
  343.     }  
  344.   
  345. }  

 

其他具体的接口只要继承BaseDao就可以了

例如:

 

Java代码   收藏代码
  1. package org.chendl.springjdbc.dao;  
  2.   
  3. import org.chendl.springjdbc.domain.Product;  
  4.   
  5. public interface ProductDao extends BaseDao<Product> {  
  6.   
  7. }  

 

 

而具体的实现类只要集成BaseDaoImpl,并实现自己的接口就可以了。

例如:

Java代码   收藏代码
  1. package org.chendl.springjdbc.dao.impl;  
  2.   
  3. import org.chendl.springjdbc.dao.ProductDao;  
  4. import org.chendl.springjdbc.domain.Product;  
  5.   
  6. public class ProductDaoImpl extends BaseDaoImpl<Product> implements ProductDao{  
  7.   
  8.       
  9. }  

 

 

补上分页的工具类:

Java代码   收藏代码
  1. package org.chendl.springjdbc.util;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class QueryResult<T> {  
  6.   
  7.     private List<T> list; // 结果集  
  8.     private int totalRow; // 总记录数  
  9.   
  10.     public QueryResult() {  
  11.     }  
  12.   
  13.     public QueryResult(List<T> list, int totalRow) {  
  14.         this.list = list;  
  15.         this.totalRow = totalRow;  
  16.     }  
  17.   
  18.     //getter and setter  
  19.   
  20. }  

 

补上生成主键的工具类:

Java代码   收藏代码
  1. package org.chendl.springjdbc.util;  
  2.   
  3. import java.util.UUID;  
  4.   
  5. public final class ToolUtil {  
  6.   
  7.     /** 
  8.      * 生成32位UUID 并去掉"-" 
  9.      */  
  10.     public static String getUUID() {  
  11.         return UUID.randomUUID().toString().replaceAll("-""");  
  12.     }  
  13.   
  14.     public static void main(String[] args) {  
  15.         System.out.println(ToolUtil.getUUID());  
  16.         System.out.println(ToolUtil.getUUID().length());// 32  
  17.     }  
  18. }  

 

 

Spring的配置文件Beans.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  7.                         http://www.springframework.org/schema/context   
  8.                         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.                         http://www.springframework.org/schema/aop   
  10.                         http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
  11.                         http://www.springframework.org/schema/tx   
  12.                         http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">  
  13.                           
  14.     <!-- 加载属性文件 -->  
  15.     <context:property-placeholder location="classpath:jdbc.properties"/>                    
  16.   
  17.     <!-- 配置数据源 -->  
  18.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  19.         <property name="driverClassName" value="${jdbc.driverClassName}"/>  
  20.         <property name="url" value="${jdbc.url}"/>  
  21.         <property name="username" value="${jdbc.username}"/>  
  22.         <property name="password" value="${jdbc.password}"/>  
  23.     </bean>  
  24.       
  25.     <!-- 配置jdbcTemplate -->  
  26.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  27.         <property name="dataSource" ref="dataSource"/>  
  28.     </bean>  
  29.       
  30.     <!-- 配置Dao -->  
  31.    
  32.     <bean id="baseDao" class="org.chendl.springjdbc.dao.impl.BaseDaoImpl" abstract="true">  
  33.         <property name="jdbcTemplate" ref="jdbcTemplate"/>  
  34.     </bean>  
  35.     <bean id="productDao" class="org.chendl.springjdbc.dao.impl.ProductDaoImpl" parent="baseDao"/>  
  36.    
  37.       
  38.     <!-- 配置事务 -->  
  39.     <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  40.         <property name="dataSource" ref="dataSource"/>  
  41.     </bean>  
  42.     <tx:advice id="txAdvice" transaction-manager="txManager">  
  43.         <tx:attributes>  
  44.             <tx:method name="*"/>  
  45.             <tx:method name="find*" read-only="true"/>  
  46.         </tx:attributes>  
  47.     </tx:advice>  
  48.     <aop:config>  
  49.         <aop:pointcut id="daoMethod" expression="execution(* org.chendl.springjdbc.dao.impl.*Impl*.*(..))" />  
  50.         <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethod"/>  
  51.     </aop:config>  
  52.   
  53. </beans>  

 

 

测试:

 

1.测试Spring的数据源

Java代码   收藏代码
  1. package junit.test;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import javax.sql.DataSource;  
  6.   
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11. import org.springframework.test.context.ContextConfiguration;  
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  13.   
  14. @RunWith(SpringJUnit4ClassRunner.class)  
  15. @ContextConfiguration(locations = { "/beans.xml" })  
  16. public class SpringTest {  
  17.   
  18.     // 测试是否取得数据库连接  
  19.     @Test  
  20.     public void testDataSource() throws SQLException {  
  21.         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");  
  22.         DataSource dataSource = ctx.getBean(DataSource.class);  
  23.         System.out.println(dataSource.getConnection());  
  24.     }  
  25. }  

 

2.测试Dao

Java代码   收藏代码
  1. package junit.test;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.LinkedHashMap;  
  5. import java.util.Map;  
  6.   
  7. import org.chendl.springjdbc.dao.ProductDao;  
  8. import org.chendl.springjdbc.domain.Product;  
  9. import org.chendl.springjdbc.util.QueryResult;  
  10. import org.chendl.springjdbc.util.ToolUtil;  
  11. import org.junit.Test;  
  12. import org.junit.runner.RunWith;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.test.context.ContextConfiguration;  
  15. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  16.   
  17. @RunWith(SpringJUnit4ClassRunner.class)  
  18. @ContextConfiguration(locations = { "/beans.xml" })  
  19. public class BaseDaoTest {  
  20.   
  21.     @Autowired  
  22.     private ProductDao dao;  
  23.   
  24.     @Test  
  25.     public void testSave() throws Exception {  
  26.         Product product = new Product();  
  27.         product.setId(ToolUtil.getUUID());  
  28.         product.setName("aaa");  
  29.         product.setAuthor("bbb");  
  30.         product.setPrice(111);  
  31.         product.setQuantity(9);  
  32.         product.setDescription("ccc");  
  33.         dao.save(product);  
  34.     }  
  35.   
  36.     @Test  
  37.     public void testUpdate() throws Exception {  
  38.         Product product = new Product();  
  39.         product.setId("79934cfd71b84cc6819d3c06b2984f80");  
  40.         product.setName("a");  
  41.         product.setAuthor("b");  
  42.         product.setPrice(444);  
  43.         product.setQuantity(44);  
  44.         product.setDescription("c");  
  45.         dao.update(product);  
  46.     }  
  47.   
  48.     @Test  
  49.     public void testDelete1() {  
  50.         Product product = new Product();  
  51.         product.setId("79934cfd71b84cc6819d3c06b2984f80");  
  52.         dao.delete(product);  
  53.     }  
  54.   
  55.     @Test  
  56.     public void testDelete2() {  
  57.         dao.delete("7030aaf8a19d4d30b26e6e2588c43c30");  
  58.     }  
  59.   
  60.     @Test  
  61.     public void testDeleteAll() {  
  62.         dao.deleteAll();  
  63.     }  
  64.   
  65.     // 插入一些测试数据  
  66.     @Test  
  67.     public void insertTestData() {  
  68.         for (int i = 1; i <= 100; i++) {  
  69.             Product product = new Product();  
  70.             product.setId(ToolUtil.getUUID());  
  71.             product.setName("springJdbc" + i);  
  72.             product.setAuthor("monday" + i);  
  73.             product.setPrice((double) Math.random() * 100);  
  74.             product.setQuantity((int) (Math.random() * 100));  
  75.             product.setDescription("介绍SpringJdbc" + i);  
  76.             dao.save(product);  
  77.         }  
  78.     }  
  79.   
  80.     // 未完成  
  81.     @Test  
  82.     public void testBatchSave() {  
  83.     }  
  84.   
  85.     // 未完成  
  86.     @Test  
  87.     public void testBatchUpdate() {  
  88.     }  
  89.   
  90.     // 未完成  
  91.     @Test  
  92.     public void testBatchDelete() {  
  93.     }  
  94.   
  95.     @Test  
  96.     public void testFindById() {  
  97.         System.out.println(dao.findById("07b5999dcb9346b3b353df18de345c31"));  
  98.     }  
  99.   
  100.     @Test  
  101.     public void testFindAll() {  
  102.         System.out.println(dao.findAll());  
  103.     }  
  104.   
  105.     // 分页  
  106.     @Test  
  107.     public void testFindByPage1() {  
  108.         int pageNo = 1;  
  109.         int pageSize = 10;  
  110.         QueryResult<Product> queryResult = dao.findByPage(pageNo, pageSize);  
  111.         for (Product p : queryResult.getList()) {  
  112.             System.out.println(p.getAuthor());  
  113.         }  
  114.     }  
  115.   
  116.     // 分页+条件  
  117.     @Test  
  118.     public void testFindByPage2() {  
  119.         int pageNo = 1;  
  120.         int pageSize = 10;  
  121.         Map<String, String> where = new HashMap<String, String>();  
  122.         where.put("author""like '%monday1%'");  
  123.         where.put("price""<90");  
  124.         QueryResult<Product> queryResult = dao.findByPage(pageNo, pageSize, where);  
  125.         for (Product p : queryResult.getList()) {  
  126.             System.out.println(p.getAuthor());  
  127.         }  
  128.     }  
  129.   
  130.     // 分页+排序  
  131.     @Test  
  132.     public void testFindByPage3() {  
  133.         int pageNo = 1;  
  134.         int pageSize = 10;  
  135.         LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();  
  136.         orderby.put("price""desc");  
  137.         orderby.put("author""asc");  
  138.         QueryResult<Product> queryResult = dao.findByPage(pageNo, pageSize, orderby);  
  139.         for (Product p : queryResult.getList()) {  
  140.             System.out.println(p.getAuthor());  
  141.         }  
  142.     }  
  143.   
  144.     // 分页+条件+排序  
  145.     @Test  
  146.     public void testFindByPage4() {  
  147.         int pageNo = 1;  
  148.         int pageSize = 10;  
  149.         Map<String, String> where = new HashMap<String, String>();  
  150.         where.put("author""like '%monday1%'");  
  151.         where.put("price""<90");  
  152.         LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();  
  153.         orderby.put("price""desc");  
  154.         orderby.put("author""asc");  
  155.         QueryResult<Product> queryResult = dao.findByPage(pageNo, pageSize, where, orderby);  
  156.         for (Product p : queryResult.getList()) {  
  157.             System.out.println(p.getAuthor());  
  158.         }  
  159.     }  
  160. }  

 

 

一些说明:

 

     这些代码的应用有些局限性,没有使用Hibernate方便。 可能还有些Bug自己没有测试出来。这里只是提供一些思路或者只是为了学习而用。之所以有这么想法是觉得单纯的使用JDBC确实有点那个(你懂的...),而使HibernateTemplate可以实现类似的Dao,那用SpringJdbc能吗?自己就试了试。就个人觉得SpringJdbc 是十分好用的。有一次写批量的时候,SpringJdbc提供的batchUpdate()方法比Hibernate的快好多。所以,就自己看来,持久层可以Hibernate+SpringJdbc搭配使用,其中批量建议使用SpringJdbc处理。(可能自己还没想到Hiberante批量性能提高的方法)。而这里基于SpringJdbc的泛型的批量方法,还没想出来。基于HibernateTemplate的倒是可以,但是性能...

这里只是自己一点学习心得仅供参考。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值