使用通用dao和通用service能夠減小代碼的開發。能夠將經常使用的增刪改查放到通用dao中。對不一樣的or框架,基本上都有本身的實現如SpringJPA的Repository就提供了經常使用的增刪改查方法。而MyBatis藉助代碼生成工具也能夠生成經常使用方法的映射java
這裏只針對Mybatis。若是使用代碼生成工具,會有一個問題:每一個Mapper裏面都有一些方法(增曬改查)。維護起來的話還好。只是在寫service的時候會有一個問題。好比UserMapper裏面有 insert(User user)
, find(Integer id)
,delete(Integer id)
等方法,則在service中也要有這些方法的實現。假設每一個Mapper有5個方法。則service也須要有5個方法的實現。若是有10個實體類。mapper能夠省略(由生成工具生成),可是service有50個方法。到後期確定很差進行維護git
該通用Mapper使用了Spring-mybatis。因此沒有實現類,而是直接調用xml文件中的同名方法。之因此將通用Mapper抽出來主要是爲了方便些通用的servicespring
package cn.liuyiyou.yishop.mapper; import java.io.Serializable; public interface BaseMapper<T,ID extends Serializable> { int deleteByPrimaryKey(ID id); int insert(T record); int insertSelective(T record); T selectByPrimaryKey(ID id); int updateByPrimaryKeySelective(T record); int updateByPrimaryKeyWithBLOBs(T record); int updateByPrimaryKey(T record); }
package cn.liuyiyou.yishop.service; import java.io.Serializable; public interface BaseService<T,ID extends Serializable> { void setBaseMapper(); int deleteByPrimaryKey(ID id); int insert(T record); int insertSelective(T record); T selectByPrimaryKey(ID id); int updateByPrimaryKeySelective(T record); int updateByPrimaryKeyWithBLOBs(T record); int updateByPrimaryKey(T record); }
package cn.liuyiyou.yishop.service.impl; import java.io.Serializable; import cn.liuyiyou.yishop.mapper.BaseMapper; import cn.liuyiyou.yishop.service.BaseService; public abstract class AbstractService<T, ID extends Serializable> implements BaseService<T, ID> { private BaseMapper<T, ID> baseMapper; public void setBaseMapper(BaseMapper<T, ID> baseMapper) { this.baseMapper = baseMapper; } @Override public int deleteByPrimaryKey(ID id) { return baseMapper.deleteByPrimaryKey(id); } @Override public int insertSelective(T record) { return baseMapper.insertSelective(record); } @Override public T selectByPrimaryKey(ID id) { return baseMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(T record) { return baseMapper.updateByPrimaryKey(record); } @Override public int updateByPrimaryKeyWithBLOBs(T record) { return baseMapper.updateByPrimaryKeyWithBLOBs(record); } @Override public int updateByPrimaryKey(T record) { return baseMapper.updateByPrimaryKey(record); } @Override