在Spring Boot项目中使用MyBatis通用 Mapper插件

MyBatis通用Mapper是一款强大的MyBatis插件,通过它可以快速实现单表的各类型CRUD业务操作,结合Mybatis Gennerator、PageHelper配合Spring Boot 通过实际项目实践,不但可以享受到MyBatis带来的优势同时也大幅提升了开发的效率。

Maven 依赖(依赖版本可自行更换到最新版本)

       
            org.mybatis
            mybatis-spring
            1.3.0
        
        
            org.mybatis
            mybatis
            3.2.8
        
        
            tk.mybatis
            mapper
            3.3.9
        
        
            com.github.pagehelper
            pagehelper
            4.1.6
        

下面是通用Mapper和PageHelper在Spring Boot下的编程式配置示例,其中包名及其他配置参数请自行替换成符合你项目的配置。

@Configuration
public class MybatisConfigurer {
    @Resource
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("cn.potato.orm.model");

        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);

        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Configuration
    @AutoConfigureAfter(MybatisConfigurer.class)
    public static class MyBatisMapperScannerConfigurer {

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
            mapperScannerConfigurer.setBasePackage("cn.potato.orm.mapper");
            //配置通用mappers
            Properties properties = new Properties();
            properties.setProperty("mappers", "cn.potato.orm.core.Mapper");
            properties.setProperty("notEmpty", "false");
            properties.setProperty("IDENTITY", "MYSQL");
            mapperScannerConfigurer.setProperties(properties);

            return mapperScannerConfigurer;
        }

    }
}

下面是使用通用Mapper来实现的一个Abstract Service可以参考使用,通过这些基础CRUD及Condition配合分页插件PageHelper完全可以实现单表的业务零SQL快速实现。

/**
 * Created by Potato on 2016/6/20.
 * 

* Service 层 基础接口,其他Service 接口 请继承该接口 * * @param the model type parameter */ public interface Service { void save(T model);//持久化 void save(List models);//批量持久化 void deleteById(Integer id);//通过主鍵刪除 void deleteByIds(String ids);//批量刪除 eg:ids -> “1,2,3,4” void update(T model);//更新 T findById(Integer id);//通过ID查找 T findBy(String property, Object value) throws TooManyResultsException; //通过某个成员属性查找,value需符合unique约束 List findByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4” List findByCondition(Condition condition);//根据条件查找 List findAll();//获取所有 }

/**
 * Created by Potato  on 2016/11/17.
 * 

* AbstractService Implement By MyBatis *

* 基于通用Mapper的MyBatis来实现Service接口的抽象Service */ public abstract class AbstractService implements Service { @Resource protected Mapper mapper; private Class modelClass; // 当前泛型真实类型的Class public AbstractService() { ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); modelClass = (Class) pt.getActualTypeArguments()[0]; } @Override public void save(T model) { mapper.insertSelective(model); } @Override public void save(List models) { mapper.insertList(models); } @Override public void deleteById(Integer id) { mapper.deleteByPrimaryKey(id); } @Override public void deleteByIds(String ids) { mapper.deleteByIds(ids); } @Override public void update(T model) { mapper.updateByPrimaryKeySelective(model); } @Override public T findById(Integer id) { return mapper.selectByPrimaryKey(id); } @Override public T findBy(String property, Object value) throws TooManyResultsException { try { T model = modelClass.newInstance(); Field field = modelClass.getDeclaredField(property); field.setAccessible(true); field.set(model, value); return mapper.selectOne(model); } catch (ReflectiveOperationException e) { //throw new ServiceException(e.getMessage(), e); 最好使用一个自定义异常 throw new RuntimeException(e.getMessage(), e); } } @Override public List findByIds(String ids) { return mapper.selectByIds(ids); } @Override public List findByCondition(Condition condition) { return mapper.selectByCondition(condition); } @Override public List findAll() { return mapper.selectAll(); } }


该插件作者已编写相应的Spring Boot Starter,在这里。
                             ---更新于,2017-3-23 .

你可能感兴趣的:(在Spring Boot项目中使用MyBatis通用 Mapper插件)