MyBatis通用Mapper是一款强大的MyBatis插件,通过它可以快速实现单表的各类型CRUD业务操作,结合Mybatis Gennerator、PageHelper配合Spring Boot 通过实际项目实践,不但可以享受到MyBatis带来的优势同时也大幅提升了开发的效率。
Maven 依赖(依赖版本可自行更换到最新版本)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
下面是通用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.
* <p>
* Service 层 基础接口,其他Service 接口 请继承该接口
*
* @param <T> the model type parameter
*/
public interface Service<T> {
void save(T model);//持久化
void save(List<T> 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<T> findByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4”
List<T> findByCondition(Condition condition);//根据条件查找
List<T> findAll();//获取所有
}
/**
* Created by Potato on 2016/11/17.
* <p>
* AbstractService Implement By MyBatis
* <p>
* 基于通用Mapper的MyBatis来实现Service接口的抽象Service
*/
public abstract class AbstractService<T> implements Service<T> {
@Resource
protected Mapper<T> mapper;
private Class<T> modelClass; // 当前泛型真实类型的Class
public AbstractService() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
@Override
public void save(T model) {
mapper.insertSelective(model);
}
@Override
public void save(List<T> 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<T> findByIds(String ids) {
return mapper.selectByIds(ids);
}
@Override
public List<T> findByCondition(Condition condition) {
return mapper.selectByCondition(condition);
}
@Override
public List<T> findAll() {
return mapper.selectAll();
}
}
该插件作者已编写相应的Spring Boot Starter,在这里。
---更新于,2017-3-23 .