spring+mybatis通用dao层、service层的一些个人理解与实现

转载自: http://blog.csdn.net/acweilisky0825/article/details/52032867


1、现在的绝大多数web应用,通常都以action、service、dao三层去组织代码,这样划分结构很清晰,分工明确

2、一般情况下,我们会把事务控制在service层。

3、action和dao层,会使用一些框架技术。比如action层可能选择有springmvc、struts等,dao层有hibernate、mybatis等选择,所以action的dao有可能遂根据情况变化,而service层关注业务逻辑,业务代码都是自己完成的,代码对自己是透明的。


基于1,我们的每个业务,可能都需要这三层代码,也就是因为一个很简单的业务,我们会写dao层及实现,service层及实现,action层,这样会造成很多的类。所以最好做到dao层必须通用,service层绝大部分通用,这样就会减少大量的类。


基于2,我们应把业务逻辑写在service层,这样才能控制住事务。例如我们的一个业务:删除A记录,插入B记录(需要在一个事务里进行),如果我们把这个业务逻辑写在了action层,我们再action层调用删除A的service,然后再调用插入B的service,如果说插入B失败了,那我们删除A这个操作将不能回滚,因为事务控制在了service层,这样写已不是一个事务。删除A操作的service已经完成,事务已经提交了,插入B的操作在另外的事务里运行。根据需要,业务逻辑尽量放在service层。通过配置spring事务控制的传播行为,在service层可以达到大部分的业务事务要求,而不需另加一层。


基于3,我们更应该把与业务相关的代码移至service层,如果service层的事务不容易控制了,可以增加额外的support层(个人理解,其实还是业务逻辑层)协助控制事务。这主要发生在我们把整个业务逻辑放在了service的一个方法,而这个方法以及调用的方法的事务配置为required(或其他),但业务的部分操作需要在不同的事务中进行,我们不想写另外的方法,也不想去更改事务配置,所以引入support层(或许你说可以把这种逻辑向action层移动,在action层处理,但记住我们的前提,action的框架是会变的,我们想尽量做到更改action层时,更简单。而且从分工来说,action层应该只关注视图逻辑,个人自扫门前雪,休管他人瓦上霜)。support层当然不是只为处理这种事务问题的,我把它定义为业务处理时需要的一些辅助层,可以协助处理业务,比如刚才说的事务问题,还有可以提供工具类支持等。 

对于dao层,应该只关注数据库连接执行结果封装这些事。


我们的通用,是基于以上的分析结论进行,下面贴上代码:

通用dao层:

  1. package com.wls.websvn.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.wls.websvn.support.Page;  
  8.   
  9. public interface CommonDao {  
  10.     /** 
  11.      *  
  12.      * 增加一个实体 
  13.      * @param pojo 
  14.      * @return 影响的行数 0失败,1成功 
  15.      */  
  16.     public <T extends Serializable> int save(T pojo);  
  17.   
  18.     /** 
  19.      *  
  20.      * 通过id删除实体 
  21.      *  
  22.      * @param clazz 
  23.      * @param id 
  24.      * @return 
  25.      */  
  26.     public <T extends Serializable> int deleteById(Class<T> clazz,  
  27.             Serializable id);  
  28.   
  29.     /** 
  30.      *  
  31.      * 通过主键获取实体 
  32.      *  
  33.      * @param clazz 
  34.      * @param id 
  35.      * @return 
  36.      */  
  37.     public <T extends Serializable> T getById(Class<T> clazz, Serializable id);  
  38.   
  39.     /** 
  40.      *  
  41.      * 查询所有实体 
  42.      *  
  43.      * @param clazz 
  44.      * @return 
  45.      */  
  46.     public <T extends Serializable> List<T> listAll(Class<T> clazz);  
  47.       
  48.     /** 
  49.      *  
  50.      * 分页查询 
  51.      *  
  52.      * @param clazz 
  53.      * @param p 
  54.      * @return 
  55.      */  
  56.     public <T extends Serializable> Page<T> pageSelect(Class<T> clazz,Page<T> p,String[]attrs,Object[]values);  
  57.       
  58.       
  59.     /** 
  60.      *  
  61.      * 分页查询时,用来统计总条数 
  62.      *  
  63.      * @param clazz 
  64.      * @param attrs 
  65.      * @param values 
  66.      * @return 
  67.      */  
  68.     public <T extends Serializable> int pageCount(Class<T> clazz,String[]attrs,Object[]values);  
  69.   
  70.     /** 
  71.      *  
  72.      * 统计总条数 
  73.      *  
  74.      * @param clazz 
  75.      * @return 
  76.      */  
  77.     public <T extends Serializable> int countAll(Class<T> clazz);  
  78.   
  79.     /** 
  80.      *  
  81.      * 指定查询使用的命名sql,查询结果封装成map 
  82.      *  
  83.      * @param statment 
  84.      * @param paraMap 
  85.      * @return 
  86.      */  
  87.     List<Map<String,Object>>  selectMap(String statment, Map<String, Object> paraMap);  
  88.   
  89. }  

dao层实现:

  1. package com.wls.websvn.dao.mybatis;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import javax.annotation.Resource;  
  9.   
  10. import org.apache.commons.lang.StringUtils;  
  11. import org.apache.ibatis.session.SqlSessionFactory;  
  12. import org.springframework.stereotype.Repository;  
  13.   
  14. import com.wls.websvn.dao.CommonDao;  
  15. import com.wls.websvn.support.Page;  
  16.   
  17. @Repository("commonDao")  
  18. public class CommonDaoImpl implements CommonDao {  
  19.   
  20.     @Resource(name = "sqlSessionFactory")  
  21.     protected SqlSessionFactory sqlSessionFactory;  
  22.   
  23.     protected <T> String getStatement(Class<T> clazz, String prefix) {  
  24.         String entityName = clazz.getSimpleName();  
  25.         if (entityName.endsWith("Model")) {  
  26.             entityName = entityName.substring(0, entityName.length() - 5);  
  27.         }  
  28.         entityName = prefix + entityName;  
  29.         return entityName;  
  30.     }  
  31.   
  32.     @Override  
  33.     public <T extends Serializable> int save(T pojo) {  
  34.         String statement = getStatement(pojo.getClass(), "insert");  
  35.         return sqlSessionFactory.openSession().insert(statement, pojo);  
  36.     }  
  37.   
  38.     @Override  
  39.     public <T extends Serializable> int deleteById(Class<T> clazz,  
  40.             Serializable id) {  
  41.         String statement = getStatement(clazz, "idDelete");  
  42.         return sqlSessionFactory.openSession().update(statement, id);  
  43.     }  
  44.   
  45.     @Override  
  46.     public <T extends Serializable> T getById(Class<T> clazz, Serializable id) {  
  47.         String statement = getStatement(clazz, "idGet");  
  48.         return sqlSessionFactory.openSession().selectOne(statement, id);  
  49.     }  
  50.   
  51.     @Override  
  52.     public <T extends Serializable> List<T> listAll(Class<T> clazz) {  
  53.         String statement = getStatement(clazz, "list");  
  54.         return sqlSessionFactory.openSession().selectList(statement);  
  55.     }  
  56.   
  57.     /** 
  58.      *  
  59.      * 组装排序串 
  60.      *  
  61.      * @param sort 
  62.      * @param order  最好将order定义成枚举类型,传递一个枚举数组 
  63.      * @return 
  64.      */  
  65.     private String genOrderStr(String sort, String order) {  
  66.         String orderBy = "";  
  67.         if (StringUtils.isNotBlank(sort)) {  
  68.             if (StringUtils.isNotBlank(order)) {  
  69.                 StringBuilder sb = new StringBuilder(" ");  
  70.                 String[] aSort = sort.split(",");  
  71.                 String[] aOrder = order.split(",");  
  72.                 for (int i = 0; i < aSort.length; i++) {  
  73.                     sb.append(aSort[i]).append(" ");  
  74.                     if (i < aOrder.length) {  
  75.                         sb.append(aOrder[i]).append(",");  
  76.                     } else {  
  77.                         sb.append("ASC").append(",");  
  78.                     }  
  79.                 }  
  80.                 // 删除最后一个,  
  81.                 sb.deleteCharAt(sb.length() - 1);  
  82.                 orderBy = sb.toString();  
  83.   
  84.             } else {  
  85.                 orderBy = " order by " + sort;  
  86.             }  
  87.         }  
  88.   
  89.         return orderBy;  
  90.     }  
  91.   
  92.     @Override  
  93.     public <T extends Serializable> int pageCount(Class<T> clazz,  
  94.             String[] attrs, Object[] values) {  
  95.         Map<String, Object> paraMap = new HashMap<String, Object>();  
  96.   
  97.         if (values != null && attrs != null) {  
  98.             for (int i = 0; i < values.length; i++) {  
  99.                 if (i < attrs.length) {  
  100.                     paraMap.put(attrs[i], values[i]);  
  101.                 }  
  102.             }  
  103.         }  
  104.         String statement = getStatement(clazz, "pageCount");  
  105.         Object o = sqlSessionFactory.openSession().selectOne(statement,paraMap);  
  106.         return Integer.parseInt(o.toString());  
  107.     }  
  108.   
  109.     @Override  
  110.     public <T extends Serializable> Page<T> pageSelect(Class<T> clazz,  
  111.             Page<T> p, String[] attrs, Object[] values) {  
  112.         int startNum = p.getStartIndex();  
  113.         int pageSize = p.getPageSize();  
  114.         String orderBy = genOrderStr(p.getSort(), p.getOrder());  
  115.         Map<String, Object> paraMap = new HashMap<String, Object>();  
  116.   
  117.         if (values != null && attrs != null) {  
  118.             for (int i = 0; i < values.length; i++) {  
  119.                 if (i < attrs.length) {  
  120.                     paraMap.put(attrs[i], values[i]);  
  121.                 }  
  122.   
  123.             }  
  124.         }  
  125.         String statement = getStatement(clazz, "page");  
  126.         p.setTotal(pageCount(clazz, attrs, values));  
  127.   
  128.         paraMap.put("startNum", startNum);  
  129.         paraMap.put("pageSize", pageSize);  
  130.         paraMap.put("endNum", startNum + pageSize);  
  131.         paraMap.put("orderBy", orderBy);  
  132.         List<T> list = sqlSessionFactory.openSession().selectList(statement,  
  133.                 paraMap);  
  134.         p.setData(list);  
  135.         return p;  
  136.     }  
  137.   
  138.     @Override  
  139.     public <T extends Serializable> int countAll(Class<T> clazz) {  
  140.         String statement = getStatement(clazz, "count");  
  141.         Object o = sqlSessionFactory.openSession().selectOne(statement);  
  142.         return Integer.parseInt(o.toString());  
  143.     }  
  144.   
  145.     @Override  
  146.     public List<Map<String, Object>> selectMap(String statement,  
  147.             Map<String, Object> paraMap) {  
  148.         return sqlSessionFactory.openSession().selectList(statement, paraMap);  
  149.     }  
  150.   
  151. }  
support:

  1. package com.wls.websvn.support;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class Page<T> {  
  6.   
  7.     /** 
  8.      * 页码 
  9.      */  
  10.     private int page = 1;  
  11.   
  12.     /** 
  13.      * 每页条数 
  14.      */  
  15.     private int pageSize = 10;  
  16.   
  17.     /** 
  18.      * 总记录数 
  19.      */  
  20.     private long total;  
  21.   
  22.     /** 
  23.      * 排序列 
  24.      */  
  25.     private String sort;  
  26.   
  27.     /** 
  28.      * 升降序 
  29.      */  
  30.     private String order;  
  31.   
  32.     /** 
  33.      * 单页数据 
  34.      */  
  35.     private List<T> data;  
  36.   
  37.     public Page() {  
  38.         this.page = 1;  
  39.         this.pageSize = 10;  
  40.     }  
  41.   
  42.       
  43.     public Page(int page, int pageSize) {  
  44.         this.page = page;  
  45.         this.pageSize = pageSize;  
  46.     }  
  47.   
  48.     /** 
  49.      * 获取page值 
  50.      * @return int page. 
  51.      */  
  52.     public int getPage() {  
  53.         return page;  
  54.     }  
  55.   
  56.     /** 
  57.      * 设置page值 
  58.      * @param page The page to set. 
  59.      */  
  60.     public void setPage(int page) {  
  61.         this.page = page;  
  62.     }  
  63.   
  64.     /** 
  65.      * 获取pageSize值 
  66.      * @return int pageSize. 
  67.      */  
  68.     public int getPageSize() {  
  69.         return pageSize;  
  70.     }  
  71.   
  72.     /** 
  73.      * 设置pageSize值 
  74.      * @param pageSize The pageSize to set. 
  75.      */  
  76.     public void setPageSize(int pageSize) {  
  77.         this.pageSize = pageSize;  
  78.     }  
  79.   
  80.     /** 
  81.      * 获取data值 
  82.      * @return List<T> data. 
  83.      */  
  84.     public List<T> getData() {  
  85.         return data;  
  86.     }  
  87.   
  88.     /** 
  89.      * 设置data值 
  90.      * @param data The data to set. 
  91.      */  
  92.     public void setData(List<T> data) {  
  93.         this.data = data;  
  94.     }  
  95.   
  96.     /** 
  97.      * 获取total值 
  98.      * @return long total. 
  99.      */  
  100.     public long getTotal() {  
  101.         return total;  
  102.     }  
  103.   
  104.     /** 
  105.      * 设置total值 
  106.      * @param total The total to set. 
  107.      */  
  108.     public void setTotal(long total) {  
  109.         this.total = total;  
  110.     }  
  111.   
  112.     public String getSort() {  
  113.         return sort;  
  114.     }  
  115.   
  116.     public void setSort(String sort) {  
  117.         this.sort = sort;  
  118.     }  
  119.   
  120.     /** 
  121.      * @return the order 
  122.      */  
  123.     public String getOrder() {  
  124.         return order;  
  125.     }  
  126.   
  127.     /** 
  128.      * @param order the order to set 
  129.      */  
  130.     public void setOrder(String order) {  
  131.         this.order = order;  
  132.     }  
  133.   
  134.     /** 
  135.      *  
  136.      * 获取分页开始的位置 
  137.      *  
  138.      * @return 
  139.      */  
  140.     public int getStartIndex() {  
  141.         if(page<1){  
  142.             return 0;  
  143.         }  
  144.         return (page - 1) * pageSize;  
  145.     }  
  146. }  
service层:

  1. package com.wls.websvn.service;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.wls.websvn.support.Page;  
  8.   
  9. public interface CommonService {  
  10.   
  11.     /** 
  12.      *  
  13.      * 增加一个实体 
  14.      * @param pojo 
  15.      * @return 影响的行数 0失败,1成功 
  16.      */  
  17.     public <T extends Serializable> int save(T pojo);  
  18.   
  19.     /** 
  20.      *  
  21.      * 通过id删除实体 
  22.      *  
  23.      * @param clazz 
  24.      * @param id 
  25.      * @return 
  26.      */  
  27.     public <T extends Serializable> int deleteById(Class<T> clazz,  
  28.             Serializable id);  
  29.   
  30.     /** 
  31.      *  
  32.      * 通过主键获取实体 
  33.      *  
  34.      * @param clazz 
  35.      * @param id 
  36.      * @return 
  37.      */  
  38.     public <T extends Serializable> T getById(Class<T> clazz, Serializable id);  
  39.   
  40.     /** 
  41.      *  
  42.      * 查询所有实体 
  43.      *  
  44.      * @param clazz 
  45.      * @return 
  46.      */  
  47.     public <T extends Serializable> List<T> listAll(Class<T> clazz);  
  48.       
  49.     /** 
  50.      *  
  51.      * 分页查询 
  52.      *  
  53.      * @param clazz 
  54.      * @param p 
  55.      * @return 
  56.      */  
  57.     public <T extends Serializable> Page<T> pageSelect(Class<T> clazz,Page<T> p,String[]attrs,Object[]values);  
  58.       
  59.       
  60.     /** 
  61.      *  
  62.      * 分页查询时,用来统计总条数 
  63.      *  
  64.      * @param clazz 
  65.      * @param attrs 
  66.      * @param values 
  67.      * @return 
  68.      */  
  69.     public <T extends Serializable> int pageCount(Class<T> clazz,String[]attrs,Object[]values);  
  70.   
  71.     /** 
  72.      *  
  73.      * 统计总条数 
  74.      *  
  75.      * @param clazz 
  76.      * @return 
  77.      */  
  78.     public <T extends Serializable> int countAll(Class<T> clazz);  
  79.   
  80.     /** 
  81.      *  
  82.      * 指定查询使用的命名sql,查询结果封装成map 
  83.      *  
  84.      * @param statment 
  85.      * @param paraMap 
  86.      * @return 
  87.      */  
  88.     List<Map<String,Object>>  selectMap(String statment, Map<String, Object> paraMap);  
  89.   
  90. }  
service层实现:

  1. package com.wls.websvn.service.impl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.springframework.stereotype.Service;  
  10.   
  11. import com.wls.websvn.dao.CommonDao;  
  12. import com.wls.websvn.service.CommonService;  
  13. import com.wls.websvn.support.Page;  
  14.   
  15. /** 
  16.  *  
  17.  * @author weilisky 
  18.  * 考虑将来可能切换到hibernate或其他框架的情况,尽量的将切换时不用变的代码移到service层。 
  19.  * 将切换时可能会变更的代码放在了dao层 
  20.  * 
  21.  */  
  22. @Service("commonService")  
  23. public class CommonServiceImpl implements CommonService {  
  24.   
  25.     @Resource(name = "commonDao")  
  26.     protected CommonDao commonDao;  
  27.   
  28.   
  29.     @Override  
  30.     public <T extends Serializable> int save(T pojo) {  
  31.         return commonDao.save(pojo);  
  32.     }  
  33.   
  34.     @Override  
  35.     public <T extends Serializable> int deleteById(Class<T> clazz,  
  36.             Serializable id) {  
  37.         return commonDao.deleteById(clazz, id);  
  38.     }  
  39.   
  40.     @Override  
  41.     public <T extends Serializable> T getById(Class<T> clazz, Serializable id) {  
  42.         return commonDao.getById(clazz, id);  
  43.     }  
  44.   
  45.     @Override  
  46.     public <T extends Serializable> List<T> listAll(Class<T> clazz) {  
  47.         return commonDao.listAll(clazz);  
  48.     }  
  49.   
  50.   
  51.     @Override  
  52.     public <T extends Serializable> int pageCount(Class<T> clazz,  
  53.             String[] attrs, Object[] values) {  
  54.         return commonDao.pageCount(clazz, attrs, values);  
  55.     }  
  56.   
  57.     @Override  
  58.     public <T extends Serializable> Page<T> pageSelect(Class<T> clazz,  
  59.             Page<T> p, String[] attrs, Object[] values) {  
  60.         return commonDao.pageSelect(clazz, p, attrs, values);  
  61.     }  
  62.   
  63.     @Override  
  64.     public <T extends Serializable> int countAll(Class<T> clazz) {  
  65.         return commonDao.countAll(clazz);  
  66.     }  
  67.   
  68.     @Override  
  69.     public List<Map<String, Object>> selectMap(String statement,  
  70.             Map<String, Object> paraMap) {  
  71.         return commonDao.selectMap(statement, paraMap);  
  72.     }  
  73.   
  74. }  
通过泛型,这里做到了service层可以查询各种实体。如果实体的操作简单,完全没有必要再写service层,commonService应该就够用,当然你还可以增加CommonService增加方法(当然可能需要同步增加CommonDao),使其更通用。

如果CommonService不够用了,你的接口应该继承CommonService接口,你的实现应该继承CommonServiceImpl实现,然后根据需要override其中的一些方法。


需要说明一下,我们把protected <T> String getStatement(Class<T> clazz, String prefix)放置在dao层,因为它并不是业务逻辑的一部分,而且对于mybaits框架,你需要这个方法,而对应hibenate你可能根本不需要(或则可以把这个方法重构到另外的一个接口)。


最后附上例子model和mapping:

  1. package com.wls.websvn.model;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Date;  
  5.   
  6. public class BaseModel implements Serializable{  
  7.   
  8.     /** 
  9.      *  
  10.      */  
  11.     private static final long serialVersionUID = -459530011111182045L;  
  12.       
  13.     protected Long id;  
  14.       
  15.     protected Date createDate;  
  16.   
  17.     public Long getId() {  
  18.         return id;  
  19.     }  
  20.   
  21.     public void setId(Long id) {  
  22.         this.id = id;  
  23.     }  
  24.   
  25.     public Date getCreateDate() {  
  26.         return createDate;  
  27.     }  
  28.   
  29.     public void setCreateDate(Date createDate) {  
  30.         this.createDate = createDate;  
  31.     }  
  32.       
  33. }  
  1. package com.wls.websvn.model;  
  2.   
  3. public class UserModel extends BaseModel {  
  4.   
  5.     /** 
  6.      *  
  7.      */  
  8.     private static final long serialVersionUID = 5715947400419117755L;  
  9.     //登录名  
  10.     private String userName;  
  11.     //真实姓名  
  12.     private String realName;  
  13.     //密码  
  14.     private String userPwd;  
  15.       
  16.     private String phoneNum;  
  17.   
  18.     public String getUserName() {  
  19.         return userName;  
  20.     }  
  21.   
  22.     public void setUserName(String userName) {  
  23.         this.userName = userName;  
  24.     }  
  25.   
  26.   
  27.     public String getRealName() {  
  28.         return realName;  
  29.     }  
  30.   
  31.     public void setRealName(String realName) {  
  32.         this.realName = realName;  
  33.     }  
  34.   
  35.     public String getUserPwd() {  
  36.         return userPwd;  
  37.     }  
  38.   
  39.     public void setUserPwd(String userPwd) {  
  40.         this.userPwd = userPwd;  
  41.     }  
  42.   
  43.     public String getPhoneNum() {  
  44.         return phoneNum;  
  45.     }  
  46.   
  47.     public void setPhoneNum(String phoneNum) {  
  48.         this.phoneNum = phoneNum;  
  49.     }  
  50.   
  51. }  
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2.   
  3. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4.   
  5. <mapper namespace="com.wls.websvn.model.UserModel">  
  6.   
  7.     <!-- PROCESSDEFINITION INSERT -->  
  8.   
  9.   
  10.     <insert id="insertUser" parameterType="com.wls.websvn.model.UserModel">  
  11.         insert into  
  12.         SVN_USER(ID_,  
  13.         NAME_, REALNAME_, PASSWORD_, MOBILEPHONE_,CREATE_TIME_)  
  14.         values  
  15.         (#{id,  
  16.         jdbcType=BIGINT},  
  17.         #{userName, jdbcType=VARCHAR},  
  18.         #{realName,  
  19.         jdbcType=VARCHAR},  
  20.         #{userPwd, jdbcType=VARCHAR},  
  21.         #{phoneNum,  
  22.         jdbcType=VARCHAR},  
  23.         #{createDate,  
  24.         jdbcType=TIMESTAMP})  
  25.     </insert>  
  26.   
  27.     <update id="idDeleteUser" parameterType="long">  
  28.         DELETE FROM  
  29.         SVN_USER WHERE ID_=#{id,jdbcType=BIGINT}  
  30.     </update>  
  31.   
  32.   
  33.     <resultMap id="userResultMap" type="com.wls.websvn.model.UserModel">  
  34.         <id property="id" column="ID_" jdbcType="BIGINT" />  
  35.         <result property="userName" column="NAME_" jdbcType="VARCHAR" />  
  36.         <result property="realName" column="REALNAME_" jdbcType="VARCHAR" />  
  37.         <result property="userPwd" column="PASSWORD_" jdbcType="VARCHAR" />  
  38.         <result property="phoneNum" column="MOBILEPHONE_" jdbcType="VARCHAR" />  
  39.         <result property="createDate" column="CREATE_TIME_" jdbcType="VARCHAR" />  
  40.     </resultMap>  
  41.   
  42.     <select id="idGetUser" parameterType="string" resultMap="userResultMap">  
  43.         SELECT *  
  44.         FROM SVN_USER WHERE ID_=#{id,jdbcType=BIGINT}  
  45.     </select>  
  46.   
  47.     <select id="countUser" resultType="int">  
  48.         SELECT COUNT(1) FROM  
  49.         SVN_USER  
  50.     </select>  
  51.   
  52.     <select id="listUser" resultMap="userResultMap">  
  53.         SELECT * FROM SVN_USER  
  54.     </select>  
  55.   
  56.     <select id="pageCountUser" resultType="int" parameterType="map">  
  57.         select count(1) from SVN_USER ST  
  58.         <where>  
  59.             <if test="id!=null and id!='' ">  
  60.                 ST.ID_ = #{id}  
  61.             </if>  
  62.             <if test="name!= null and name!= '' ">  
  63.                 AND ST.NAME_ LIKE CONCAT(CONCAT('%', #{name}),'%')  
  64.             </if>  
  65.             <if test="codePrefix !=null and codePrefix!='' ">  
  66.                 AND ST.CODEPREFIX_ = #{codePrefix}  
  67.             </if>  
  68.             <if test="active !=null ">  
  69.                 AND ST.ACTIVE_ = #{active}  
  70.             </if>  
  71.             <if test="description !=null and description!='' ">  
  72.                 AND ST.DESCRIPTION_ = #{description}  
  73.             </if>  
  74.         </where>  
  75.     </select>  
  76.   
  77.   
  78.     <select id="pageUser" resultMap="userResultMap"  
  79.         parameterType="map">  
  80.         select * from SVN_USER ST  
  81.         <where>  
  82.             <if test="id!=null and id!='' ">  
  83.                 ST.ID_ = #{id}  
  84.             </if>  
  85.             <if test="name!= null and name!= '' ">  
  86.                 AND ST.NAME_ LIKE CONCAT(CONCAT('%', #{name}),'%')  
  87.             </if>  
  88.             <if test="codePrefix !=null and codePrefix!='' ">  
  89.                 AND ST.CODEPREFIX_ = #{codePrefix}  
  90.             </if>  
  91.             <if test="active !=null ">  
  92.                 AND ST.ACTIVE_ = #{active}  
  93.             </if>  
  94.             <if test="description !=null and description!='' ">  
  95.                 AND ST.DESCRIPTION_ = #{description}  
  96.             </if>  
  97.         </where>  
  98.         <if test="startNum!=null">  
  99.             LIMIT ${startNum} , ${pageSize}  
  100.         </if>  
  101.   
  102.         <if test="orderBy!=null and orderBy!='' ">  
  103.             ${orderBy}  
  104.         </if>  
  105.   
  106.     </select>  
  107.   
  108.   
  109.     <select id="selectMap" resultType="map" parameterType="map">  
  110.         SELECT *  
  111.         FROM SVN_USER  
  112.     </select>  
  113.   
  114. </mapper>  
部分spring配置:

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="${initialSize}"></property>
		<!-- 连接池最大数量 -->
		<property name="maxActive" value="${maxActive}"></property>
		<!-- 连接池最大空闲 -->
		<property name="maxIdle" value="${maxIdle}"></property>
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="${minIdle}"></property>
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="${maxWait}"></property>
	</bean>

	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自动扫描mapping.xml文件 -->
		<property name="mapperLocations" value="classpath:com/wls/websvn/mapping/*.xml"></property>
	</bean>

	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<!-- 	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.wls.websvn.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
 -->
	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>


</beans>
applicationContext-service.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:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
  7.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"  
  9.     default-lazy-init="true">  
  10.     <aop:config>  
  11.         <aop:advisor id="managerTx" advice-ref="txAdvice"  
  12.             pointcut="execution(* *..service.*Manager.*(..))" order="0" />  
  13.   
  14.         <aop:advisor id="managerTxService" advice-ref="txAdvice"  
  15.             pointcut="execution(* *..service.*Service.*(..))" order="1" />  
  16.   
  17.     </aop:config>  
  18.   
  19.     <!-- Enable @Transactional support -->  
  20.     <tx:annotation-driven transaction-manager="transactionManager" />  
  21.   
  22.     <!-- Enable @AspectJ support -->  
  23.     <aop:aspectj-autoproxy proxy-target-class="true" />  
  24.   
  25.     <!-- Activates scanning of @Autowired -->  
  26.     <context:annotation-config />  
  27.   
  28.     <!-- Activates scanning of @Service -->  
  29.     <context:component-scan base-package="com.dcfs.qed" />  
  30.   
  31.   
  32.     <tx:advice id="txAdvice">  
  33.         <tx:attributes>  
  34.             <tx:method name="get*" read-only="true" />  
  35.             <tx:method name="set*" read-only="true" />  
  36.             <tx:method name="exist*" read-only="true" />  
  37.             <tx:method name="find*" read-only="true" />  
  38.             <tx:method name="load*" read-only="true" />  
  39.             <tx:method name="query*" read-only="true" />  
  40.             <tx:method name="list*" read-only="true" />  
  41.             <tx:method name="paging*" read-only="true" />  
  42.   
  43.             <tx:method name="update*" propagation="REQUIRED"  
  44.                 rollback-for="Exception" />  
  45.             <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />  
  46.             <tx:method name="remove*" propagation="REQUIRED"  
  47.                 rollback-for="Exception" />  
  48.             <tx:method name="save*" propagation="REQUIRED"  
  49.                 rollback-for="Exception" />  
  50.   
  51.             <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />  
  52.   
  53.             <tx:method name="create*" propagation="REQUIRED"  
  54.                 rollback-for="Exception" />  
  55.         </tx:attributes>  
  56.     </tx:advice>  
  57. </beans>  
hibernate的通用下次再整理
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值