基于mybatis的BaseDao及BaseService深度结合

来源:互联网 发布:淘宝天猫客服招聘 编辑:程序博客网 时间:2024/06/14 05:33

mybatis帮助程序猿省去了很多工作了,需要结合好BaseDao与BaseService,这里就提供下我所使用的BaseXXX。

前提,mybatis的映射文件是采用mybatis-generator自动生成的(mybatis-generator使用方法)


1、BaseDao,我们知道在mybatis与SpringMVC结合的时候,Dao层只需要写interface即可,剩下的实现工作将由mybatis自动为我们实现,这个BaseDao省去interface这层,采用SpringMvc的@Repository标签进行注入管理,上代码:

[java] view plain copy
 print?
  1. import java.io.Serializable;  
  2. import java.lang.reflect.InvocationTargetException;  
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.apache.commons.beanutils.PropertyUtils;  
  8. import org.apache.ibatis.session.RowBounds;  
  9. import org.apache.ibatis.session.SqlSessionFactory;  
  10. import org.mybatis.spring.support.SqlSessionDaoSupport;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Repository;  
  13.   
  14. import com.alibaba.dubbo.common.utils.CollectionUtils;  
  15. import com.github.pagehelper.PageHelper;  
  16. import com.github.pagehelper.PageInfo;  
  17. //工具类  
  18. import com.ivan.core.util.GenericsUtils;  
  19. //分页Form  
  20. import com.ivan.core.util.page.PageForm;  
  21.   
  22. @Repository("baseDao")  
  23. public class BaseDao<T, PK extends Serializable> extends SqlSessionDaoSupport implements Serializable {  
  24.       
  25.     private static final long serialVersionUID = 7623507504198633838L;  
  26.   
  27.     private final String POSTFIX = "Dao";  
  28.   
  29.     private final String _INSERT = ".insert";  
  30.   
  31.     private final String _INSERTSELECTIVE = ".insertSelective";  
  32.   
  33.     private final String _SELECTBYPRIMARYKEY = ".selectByPrimaryKey";  
  34.   
  35.     private final String _UPDATEBYPRIMARYKEY = ".updateByPrimaryKey";  
  36.   
  37.     private final String _UPDATEBYPRIMARYKEYSELECTIVE = ".updateByPrimaryKeySelective";  
  38.   
  39.     private final String _DELETEBYPRIMARYKEY = ".deleteByPrimaryKey";  
  40.       
  41.     @Autowired  
  42.     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {  
  43.         super.setSqlSessionFactory(sqlSessionFactory);  
  44.     }  
  45.     /*GenericsUtils为工具类,请见下方代码 
  46.           泛型获得XXXEntity,将其转换为XXXEntityDao,具体操作替换掉Entity变成XXXDao,对应Mapper.xml中的namespace命名 
  47.         */  
  48.     @SuppressWarnings({ "unchecked""rawtypes" })  
  49.     public String getNampSpace() {  
  50.         Class<T> clazz = (Class)GenericsUtils.getSuperClassGenricType(this.getClass());  
  51.         String simpleName = clazz.getSimpleName() + POSTFIX;  
  52.         return simpleName;  
  53.     }  
  54.       
  55.     public int insert(T entity) {  
  56.         return getSqlSession().insert(  
  57.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  58.                         : this.getNampSpace()) + _INSERT, entity);  
  59.     }  
  60.       
  61.       
  62.     public int insertSelective(T record) {  
  63.         return getSqlSession().insert(  
  64.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  65.                         : this.getNampSpace()) + _INSERTSELECTIVE, record);  
  66.     }  
  67.   
  68.     public T selectByPrimaryKey(PK id) {  
  69.         return getSqlSession().selectOne(  
  70.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  71.                         : this.getNampSpace()) + _SELECTBYPRIMARYKEY, id);  
  72.     }  
  73.   
  74.       
  75.     public int updateByPrimaryKey(T record) {  
  76.         return getSqlSession().update(  
  77.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  78.                         : this.getNampSpace()) + _UPDATEBYPRIMARYKEY, record);  
  79.     }  
  80.   
  81.     public int updateByPrimaryKeySelective(T record) {  
  82.         return getSqlSession().update(  
  83.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  84.                         : this.getNampSpace()) + _UPDATEBYPRIMARYKEYSELECTIVE, record);  
  85.     }  
  86.   
  87.     public int deleteByPrimaryKey(PK id) {  
  88.         return getSqlSession().delete(  
  89.                 (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity""")  
  90.                         : this.getNampSpace()) + _DELETEBYPRIMARYKEY, id);  
  91.     }  
  92.   
  93.     @SuppressWarnings({ "rawtypes""unchecked" })  
  94.     public PageInfo<T> pageFind(String statementKey, PageForm pageForm, Object parameter,  
  95.             Boolean isSimplePage) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  96.         Map params = new HashMap();  
  97.         if (parameter != null) {  
  98.             if (parameter instanceof Map) {  
  99.                 params.putAll((Map) parameter);  
  100.             } else {  
  101.                 Map parameterObject = PropertyUtils.describe(parameter);  
  102.                 params.putAll(parameterObject);  
  103.             }  
  104.         }  
  105.         PageHelper.startPage(pageForm.getPage(), pageForm.getRows());  
  106.         List<T> list = getSqlSession().selectList(statementKey, params);  
  107.         PageInfo<T> pageInfo = new PageInfo(list);  
  108.   
  109.         return pageInfo;  
  110.     }  
  111.   
  112.     @SuppressWarnings({ "rawtypes""unchecked" })  
  113.     public List<T> findTop(int top, String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  114.         Map params = new HashMap();  
  115.         if (parameter != null) {  
  116.             if (parameter instanceof Map) {  
  117.                 params.putAll((Map) parameter);  
  118.             } else {  
  119.                 Map parameterObject = PropertyUtils.describe(parameter);  
  120.                 params.putAll(parameterObject);  
  121.             }  
  122.         }  
  123.         List<T> list = getSqlSession().selectList(statementKey, params, new RowBounds(0, top));  
  124.         return list;  
  125.     }  
  126.   
  127.     public T findTopOne(String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  128.         List<T> list = findTop(1, statementKey, parameter);  
  129.         return CollectionUtils.isEmpty(list) ? null : list.get(0);  
  130.     }  
  131.       
  132.     @SuppressWarnings({ "rawtypes""unchecked" })  
  133.     public <M> PageInfo<M> pageFindModel(String statementKey, PageForm pageForm, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  134.         Map params = new HashMap();  
  135.         if (parameter != null) {  
  136.             if (parameter instanceof Map) {  
  137.                 params.putAll((Map) parameter);  
  138.             } else {  
  139.                 Map parameterObject = PropertyUtils.describe(parameter);  
  140.                 params.putAll(parameterObject);  
  141.             }  
  142.         }  
  143.         PageHelper.startPage(pageForm.getPage(), pageForm.getRows());  
  144.         List<M> list = getSqlSession().selectList(statementKey, params);  
  145.         PageInfo<M> pageInfo = new PageInfo(list);  
  146.   
  147.         return pageInfo;  
  148.     }  
  149. }  
2、泛型工具类,GenericsUtils:

[java] view plain copy
 print?
  1. import java.lang.reflect.Field;  
  2. import java.lang.reflect.Method;  
  3. import java.lang.reflect.ParameterizedType;  
  4. import java.lang.reflect.Type;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Random;  
  8.   
  9. import javax.servlet.http.HttpSession;  
  10.   
  11. import org.springframework.web.context.request.RequestContextHolder;  
  12. import org.springframework.web.context.request.ServletRequestAttributes;  
  13.   
  14. /** 
  15.  * 泛型工具类 
  16.  *  
  17.  * @author <a href="http://www.blogjava.net/lishunli/" 
  18.  *         target="_jeecg">ShunLi</a> 
  19.  * @notes Created on 2010-1-21<br> 
  20.  *        Revision of last commit:$Revision: 1.1 $<br> 
  21.  *        Author of last commit:$Author: ghp $<br> 
  22.  *        Date of last commit:$Date: 2010-01-25 16:48:17 +0800 (周一, 25 一月 2010) 
  23.  *        $<br> 
  24.  *        <p> 
  25.  */  
  26. public class GenericsUtils {  
  27.     /** 
  28.      * 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
  29.      *  
  30.      * @param clazz 
  31.      *            clazz 需要反射的类,该类必须继承范型父类 
  32.      * @param index 
  33.      *            泛型参数所在索引,从0开始. 
  34.      * @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  35.      *         <code>Object.class</code> 
  36.      */  
  37.     public static Class getSuperClassGenricType(Class clazz, int index) {  
  38.         Type genType = clazz.getGenericSuperclass();// 得到泛型父类  
  39.         // 如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class  
  40.         if (!(genType instanceof ParameterizedType)) {  
  41.             return Object.class;  
  42.         }  
  43.         // 返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends  
  44.         // DaoSupport<Buyer,Contact>就返回Buyer和Contact类型  
  45.         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
  46.         if (index >= params.length || index < 0) {  
  47.             throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));  
  48.         }  
  49.         if (!(params[index] instanceof Class)) {  
  50.             return Object.class;  
  51.         }  
  52.         return (Class) params[index];  
  53.     }  
  54.   
  55.     /** 
  56.      * 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
  57.      *  
  58.      * @param clazz 
  59.      *            clazz 需要反射的类,该类必须继承泛型父类 
  60.      * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  61.      *         <code>Object.class</code> 
  62.      */  
  63.     @SuppressWarnings("unchecked")  
  64.     public static Class getSuperClassGenricType(Class clazz) {  
  65.         return getSuperClassGenricType(clazz, 0);  
  66.     }  
  67.   
  68.     /** 
  69.      * 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){} 
  70.      *  
  71.      * @param Method 
  72.      *            method 方法 
  73.      * @param int index 泛型参数所在索引,从0开始. 
  74.      * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  75.      *         <code>Object.class</code> 
  76.      */  
  77.     @SuppressWarnings("unchecked")  
  78.     public static Class getMethodGenericReturnType(Method method, int index) {  
  79.         Type returnType = method.getGenericReturnType();  
  80.         if (returnType instanceof ParameterizedType) {  
  81.             ParameterizedType type = (ParameterizedType) returnType;  
  82.             Type[] typeArguments = type.getActualTypeArguments();  
  83.             if (index >= typeArguments.length || index < 0) {  
  84.                 throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));  
  85.             }  
  86.             return (Class) typeArguments[index];  
  87.         }  
  88.         return Object.class;  
  89.     }  
  90.   
  91.     /** 
  92.      * 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){} 
  93.      *  
  94.      * @param Method 
  95.      *            method 方法 
  96.      * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  97.      *         <code>Object.class</code> 
  98.      */  
  99.     @SuppressWarnings("unchecked")  
  100.     public static Class getMethodGenericReturnType(Method method) {  
  101.         return getMethodGenericReturnType(method, 0);  
  102.     }  
  103.   
  104.     /** 
  105.      * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, 
  106.      * Buyer> maps, List<String> names){} 
  107.      *  
  108.      * @param Method 
  109.      *            method 方法 
  110.      * @param int index 第几个输入参数 
  111.      * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合 
  112.      */  
  113.     @SuppressWarnings("unchecked")  
  114.     public static List<Class> getMethodGenericParameterTypes(Method method, int index) {  
  115.         List<Class> results = new ArrayList<Class>();  
  116.         Type[] genericParameterTypes = method.getGenericParameterTypes();  
  117.         if (index >= genericParameterTypes.length || index < 0) {  
  118.             throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));  
  119.         }  
  120.         Type genericParameterType = genericParameterTypes[index];  
  121.         if (genericParameterType instanceof ParameterizedType) {  
  122.             ParameterizedType aType = (ParameterizedType) genericParameterType;  
  123.             Type[] parameterArgTypes = aType.getActualTypeArguments();  
  124.             for (Type parameterArgType : parameterArgTypes) {  
  125.                 Class parameterArgClass = (Class) parameterArgType;  
  126.                 results.add(parameterArgClass);  
  127.             }  
  128.             return results;  
  129.         }  
  130.         return results;  
  131.     }  
  132.   
  133.     /** 
  134.      * 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> 
  135.      * maps, List<String> names){} 
  136.      *  
  137.      * @param Method 
  138.      *            method 方法 
  139.      * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合 
  140.      */  
  141.     @SuppressWarnings("unchecked")  
  142.     public static List<Class> getMethodGenericParameterTypes(Method method) {  
  143.         return getMethodGenericParameterTypes(method, 0);  
  144.     }  
  145.   
  146.     /** 
  147.      * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names; 
  148.      *  
  149.      * @param Field 
  150.      *            field 字段 
  151.      * @param int index 泛型参数所在索引,从0开始. 
  152.      * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  153.      *         <code>Object.class</code> 
  154.      */  
  155.     @SuppressWarnings("unchecked")  
  156.     public static Class getFieldGenericType(Field field, int index) {  
  157.         Type genericFieldType = field.getGenericType();  
  158.   
  159.         if (genericFieldType instanceof ParameterizedType) {  
  160.             ParameterizedType aType = (ParameterizedType) genericFieldType;  
  161.             Type[] fieldArgTypes = aType.getActualTypeArguments();  
  162.             if (index >= fieldArgTypes.length || index < 0) {  
  163.                 throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));  
  164.             }  
  165.             return (Class) fieldArgTypes[index];  
  166.         }  
  167.         return Object.class;  
  168.     }  
  169.   
  170.     /** 
  171.      * 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names; 
  172.      *  
  173.      * @param Field 
  174.      *            field 字段 
  175.      * @param int index 泛型参数所在索引,从0开始. 
  176.      * @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
  177.      *         <code>Object.class</code> 
  178.      */  
  179.     @SuppressWarnings("unchecked")  
  180.     public static Class getFieldGenericType(Field field) {  
  181.         return getFieldGenericType(field, 0);  
  182.     }  
  183. /** 
  184.  * 根据实体得到实体的所有属性 
  185.  * @param objClass 
  186.  * @return 
  187.  * @throws ClassNotFoundException 
  188.  */  
  189.     public static String[] getColumnNames(String objClass) throws ClassNotFoundException {  
  190.         String[] wageStrArray = null;  
  191.         if (objClass != null) {  
  192.             Class class1 = Class.forName(objClass);  
  193.             Field[] field = class1.getDeclaredFields();// 这里便是获得实体Bean中所有属性的方法  
  194.             StringBuffer sb = new StringBuffer();  
  195.             for (int i = 0; i < field.length; i++) {// 这里不多说了  
  196.   
  197.                 sb.append(field[i].getName());  
  198.   
  199.                 // 这是分割符 是为了去掉最后那个逗号  
  200.   
  201.                 // 比如 如果不去最后那个逗号 最后打印出来的结果是 "id,name,"  
  202.   
  203.                 // 去了以后打印出来的是 "id,name"  
  204.                 if (i < field.length - 1) {  
  205.                     sb.append(",");  
  206.   
  207.                 }  
  208.             }  
  209.   
  210.             // split(",");这是根据逗号来切割字符串使字符串变成一个数组  
  211.   
  212.             wageStrArray = sb.toString().split(",");  
  213.             return wageStrArray;  
  214.         } else {  
  215.             return wageStrArray;  
  216.         }  
  217.     }  
  218.     public static Object[] field2Value(Field[] f, Object o) throws Exception {  
  219.         Object[] value = new Object[f.length];  
  220.         for (int i = 0; i < f.length; i++) {  
  221.             value[i] = f[i].get(o);  
  222.         }  
  223.         return value;  
  224.     }  
  225.     /** 
  226.      * returns the current http session object 
  227.      *  
  228.      * @return session 
  229.      */  
  230.     public HttpSession getSession() {     
  231.         HttpSession session=null;  
  232.         ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();  
  233.         HttpSession contextSess = attr == null ? session : attr.getRequest().getSession(true);  
  234.           
  235.         return contextSess;   
  236.     }  
  237.     /** 
  238.      * 得到实体类 
  239.      * @param objClass 实体类包含包名 
  240.      * @return 
  241.      */  
  242.      public static  Class getEntityClass(String objClass){  
  243.          Class entityClass = null;  
  244.         try {  
  245.             entityClass = Class.forName(objClass);  
  246.         } catch (ClassNotFoundException e) {              
  247.             e.printStackTrace();  
  248.         }   
  249.          return entityClass;  
  250.      }    
  251.        
  252.      /** 
  253.          * 定义字符集 
  254.          * @param  
  255.          * @return 
  256.          */  
  257.     private static char[] chars = { '0''1''2''3''4''5''6''7',   
  258.              '8''9''a''b''c''d''e''f''g''h''i''j''k',   
  259.              'l''m''n''o''p''q''r''s''t''u''v''w''x',   
  260.              'y''z''A''B','C''D''E''F''G''H''I''J''K''L',   
  261.              'M''N''O''P''Q''R''S''T''U''V''W''X''Y',   
  262.              'Z'};    //72个字符集   
  263.   
  264.            /**  
  265.            *  
  266.            * @param passLength  
  267.            *            随机密码长度  
  268.            * @param count  
  269.            *            随机密码个数  
  270.            * @return 随机密码数组  
  271.            */   
  272.            public static String getPasswords(int passLength) {   
  273.             String passwords = "";// 新建一个长度为指定需要密码个数的字符串数组   
  274.             Random random = new Random();   
  275.             StringBuilder password = new StringBuilder("");// 保存生成密码的变量   
  276.             for (int m = 1; m <= passLength; m++) {// 内循环 从1开始到密码长度 正式开始生成密码   
  277.               password.append(chars[random.nextInt(62)]);// 为密码变量随机增加上面字符中的一个   
  278.             }   
  279.             passwords = password.toString();// 将生成出来的密码赋值给密码数组   
  280.             return passwords;   
  281.            }   
  282.   
  283.   
  284. }  

3、BaseService接口,为什么这层要选择接口来实现呢?有很多需要前后分离的应用,暴露的服务就是接口暴露Service层,所以采用接口。

[java] view plain copy
 print?
  1. import java.io.Serializable;  
  2. import java.lang.reflect.InvocationTargetException;  
  3. import java.util.List;  
  4.   
  5. @SuppressWarnings("hiding")  
  6. public interface BaseService<T, Serializable> {  
  7.       
  8.     public int insert(T record);  
  9.     public int insertSelective(T record);  
  10.     public T selectByPrimaryKey(String id);  
  11.     public int updateByPrimaryKey(T record);  
  12.     public int updateByPrimaryKeySelective(T record);  
  13.     public int deleteByPrimaryKey(String id);  
  14.     public List<T> findTop(int top, String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException;  
  15.     public T findTopOne(String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException;  
  16. }  

4、BaseService接口的实现类BaseServiceImpl,需要注入BaseDao(其中必须对BaseDao进行set,否则无法获取具体泛型)

[java] view plain copy
 print?
  1. import java.io.Serializable;  
  2. import java.lang.reflect.InvocationTargetException;  
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import com.alibaba.dubbo.config.annotation.Service;  
  8. import com.ivan.api.base.BaseService;  
  9. import com.ivan.base.BaseDao;  
  10.   
  11. @Service  
  12. public abstract class BaseServiceImpl<T> implements BaseService<T, Serializable>{  
  13.       
  14.     @Autowired  
  15.     private BaseDao<T, Serializable> baseDao;  
  16.       
  17.     public BaseDao<T, Serializable> getBaseDao() {  
  18.         return baseDao;  
  19.     }  
  20.     public void setBaseDao(BaseDao<T, Serializable> baseDao) {  
  21.         this.baseDao = baseDao;  
  22.     }  
  23.   
  24.     public int insert(T entity) {  
  25.         return baseDao.insert(entity);  
  26.     }  
  27.   
  28.     public int insertSelective(T record) {  
  29.         return baseDao.insertSelective(record);  
  30.     }  
  31.   
  32.     public T selectByPrimaryKey(String id) {  
  33.         return baseDao.selectByPrimaryKey(id);  
  34.     }  
  35.   
  36.     public int updateByPrimaryKey(T record) {  
  37.         return baseDao.updateByPrimaryKey(record);  
  38.     }  
  39.   
  40.     public int updateByPrimaryKeySelective(T record) {  
  41.         return baseDao.updateByPrimaryKeySelective(record);  
  42.     }  
  43.   
  44.     public int deleteByPrimaryKey(String id) {  
  45.         return baseDao.deleteByPrimaryKey(id);  
  46.     }  
  47.   
  48.     public List<T> findTop(int top, String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  49.         return baseDao.findTop(top, statementKey, parameter);  
  50.     }  
  51.   
  52.     public T findTopOne(String statementKey, Object parameter) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {  
  53.         return baseDao.findTopOne(statementKey, parameter);  
  54.     }  
  55. }  

5、Mapper.xml文件的定义,需要注意的是namespace的命名,会通过这个命名找到具体的mapper文件,进行数据的操作。

[java] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="UserDao" >  
  4.   <resultMap id="BaseResultMap" type="com.ivan.entity.UserEntity" >  
  5.     <id column="id" property="id" jdbcType="VARCHAR" />  
  6.     <result column="name" property="name" jdbcType="VARCHAR" />  
  7.     <result column="age" property="age" jdbcType="INTEGER" />  
  8.   </resultMap>  
  9.   <sql id="Base_Column_List" >  
  10.     id, name, age  
  11.   </sql>  
  12.     
  13.   <select id="selectAll" resultMap="BaseResultMap">  
  14.     select  
  15.     <include refid="Base_Column_List" />  
  16.     from user  
  17.   </select>  
  18.     
  19.   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="String" >  
  20.     select   
  21.     <include refid="Base_Column_List" />  
  22.     from user  
  23.     where id = #{id,jdbcType=INTEGER}  
  24.   </select>  
  25.   <delete id="deleteByPrimaryKey" parameterType="String" >  
  26.     delete from user  
  27.     where id = #{id,jdbcType=INTEGER}  
  28.   </delete>  
  29.   <insert id="insert" parameterType="com.ivan.entity.UserEntity" >  
  30.     insert into user (id, name, age  
  31.       )  
  32.     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}  
  33.       )  
  34.   </insert>  
  35.   <insert id="insertSelective" parameterType="com.ivan.entity.UserEntity" >  
  36.     insert into user  
  37.     <trim prefix="(" suffix=")" suffixOverrides="," >  
  38.       <if test="id != null" >  
  39.         id,  
  40.       </if>  
  41.       <if test="name != null" >  
  42.         name,  
  43.       </if>  
  44.       <if test="age != null" >  
  45.         age,  
  46.       </if>  
  47.     </trim>  
  48.     <trim prefix="values (" suffix=")" suffixOverrides="," >  
  49.       <if test="id != null" >  
  50.         #{id,jdbcType=VARCHAR},  
  51.       </if>  
  52.       <if test="name != null" >  
  53.         #{name,jdbcType=VARCHAR},  
  54.       </if>  
  55.       <if test="age != null" >  
  56.         #{age,jdbcType=INTEGER},  
  57.       </if>  
  58.     </trim>  
  59.   </insert>  
  60.   <update id="updateByPrimaryKeySelective" parameterType="com.ivan.entity.UserEntity" >  
  61.     update user  
  62.     <set >  
  63.       <if test="name != null" >  
  64.         name = #{name,jdbcType=VARCHAR},  
  65.       </if>  
  66.       <if test="age != null" >  
  67.         age = #{age,jdbcType=INTEGER},  
  68.       </if>  
  69.     </set>  
  70.     where id = #{id,jdbcType=VARCHAR}  
  71.   </update>  
  72.   <update id="updateByPrimaryKey" parameterType="com.ivan.entity.UserEntity" >  
  73.     update user  
  74.     set name = #{name,jdbcType=VARCHAR},  
  75.       age = #{age,jdbcType=INTEGER}  
  76.     where id = #{id,jdbcType=VARCHAR}  
  77.   </update>  
  78. </mapper>  



6、具体的使用方法:

a、定义UserDao:

[java] view plain copy
 print?
  1. @Repository("userDao")  
  2. public class UserDao extends BaseDao<UserEntity, Serializable>{  
  3.   
  4.     /** 
  5.      *  
  6.      */  
  7.     private static final long serialVersionUID = 9152785684346322571L;  
  8.   
  9. }  
b、定义UserService接口

[java] view plain copy
 print?
  1. public interface UserService extends BaseService<UserEntity, Serializable>{  
  2.           
  3. }  

c、实现UserService接口

[java] view plain copy
 print?
  1. @Service  
  2. public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService{  
  3.       
  4. }  

d、调用UserService接口

[java] view plain copy
 print?
  1. @Controller  
  2. @RequestMapping("/user")  
  3. public class UserController {  
  4.       
  5.     @SuppressWarnings("unused")  
  6.     private static final Logger logger = LoggerFactory.getLogger(UserController.class);  
  7.       
  8.     @Reference  
  9.     private UserService userService;  
  10. }  

以上,可以整合到前几篇关于dubbo的工程中。

0 0
原创粉丝点击