SpringBoot集成Mybatis三剑客

in 笔记 with 0 comment

三剑客

Mybatis、Mybatis通用Mapper、MybatisPageHelper

引入依赖

<!--mybatis-->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
   <groupId>tk.mybatis</groupId>
   <artifactId>mapper-spring-boot-starter</artifactId>
   <version>1.1.4</version>
</dependency>
<!--pagehelper-->
<dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper-spring-boot-starter</artifactId>
   <version>1.2.1</version>
</dependency>

编写实体类Entity

编写自定义Mapper

public interface MyMapper<T>
        extends
        BaseMapper<T>,
        ConditionMapper<T>,
        IdsMapper<T>,
        InsertListMapper<T> {

    //FIXME 特别注意,该接口不能被扫描到,否则会出错
}

编写持久化Mapper

public interface UserMapper extends MyMapper<User> {

}

编写通用BaseService

/**
 * BaseService 层 基础接口,其他Service 接口 请继承该接口
 */
public interface BaseService<T> {
    void save(T model);//持久化
    void save(List<T> models);//批量持久化
    void deleteById(Long id);//通过主鍵刪除
    void deleteByIds(String ids);//批量刪除 eg:ids -> “1,2,3,4”
    void update(T model);//更新
    T findById(Long id);//通过ID查找
    T findBy(String fieldName, Object value) throws TooManyResultsException; //通过Model中某个成员变量名称(非数据表中column的名称)查找,value需符合unique约束
    List<T> findByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4”
    List<T> findByCondition(Condition condition);//根据条件查找
    List<T> findAll();//获取所有
}

实现BaseService模板

/**
 * 基于通用MyBatis Mapper插件的Service接口的实现
 */
public abstract class BaseServiceImpl<T> implements BaseService<T>{

    @Autowired
    protected MyMapper<T> mapper;

    private Class<T> modelClass;    // 当前泛型真实类型的Class

    public BaseServiceImpl() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    public void save(T model) {
        mapper.insertSelective(model);
    }

    public void save(List<T> models) {
        mapper.insertList(models);
    }

    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void deleteByIds(String ids) {
        mapper.deleteByIds(ids);
    }

    public void update(T model) {
        mapper.updateByPrimaryKeySelective(model);
    }

    public T findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public T findBy(String fieldName, Object value) throws TooManyResultsException {
        try {
            T model = modelClass.newInstance();
            Field field = modelClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(model, value);
            return mapper.selectOne(model);
        } catch (ReflectiveOperationException e) {
            throw new ServiceException(e.getMessage(), e);
        }
    }

    public List<T> findByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    public List<T> findByCondition(Condition condition) {
        return mapper.selectByCondition(condition);
    }

    public List<T> findAll() {
        return mapper.selectAll();
    }
}

用法实例

service继承BaseService,serviceImp继承BaseServiceImpl并实现该service

public interface UserService extends BaseService<User>{
}
@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
}

在application添加三剑客的配置

#mybatis
mybatis.type-aliases-package=com.bixuange.usermanagerserver.model
mybatis.mapper-locations=classpath:mapper/*.xml

#mapper
mapper.mappers=com.bixuange.usermanageserver.common.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL

#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

添加到Spring容器

程序入口添加mapper的扫描

@EnableEurekaClient
@SpringBootApplication
@MapperScan(basePackages = "com.bixuange.usermanageserver.dao")
public class UserserviceApplication {

   public static void main(String[] args) {
      SpringApplication.run(UserserviceApplication.class, args);
   }
}