Hello大家好,本章我們整合通用 Mapper功能 。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝
一:什麼是通用 Mapper
通用 Mapper 是一個可以實現任意 MyBatis 通用方法的框架,專案提供了常規的增刪改查操作以及Example
相關的單表操作。通用 Mapper 是為了解決 MyBatis 使用中 90% 的基本操作,使用它可以很方便的進行開發,可以節省開發人員大量的時間。
二:新增mapper依賴
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>複製程式碼
三:修改MybatisConfigurer配置檔案
這裡我們重新配置MapperScannerConfigurer
開啟MybatisConfigurer
將import org.mybatis.spring.mapper.MapperScannerConfigurer;修改為
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
四:建立通用mapper,service,serviceImpl
建立core→universal資料夾
建立以下檔案
1、Mapper
package com.example.demo.core.universal;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.common.ConditionMapper;
import tk.mybatis.mapper.common.IdsMapper;
import tk.mybatis.mapper.common.special.InsertListMapper;
/**
* @Description: 定製版MyBatis Mapper外掛介面,如需其他介面參考官方文件自行新增。
* @author 張瑤
* @date 2018/4/22 21:15
*/
public interface Mapper<T> extends BaseMapper<T>, ConditionMapper<T>, IdsMapper<T>, InsertListMapper<T> {
}
複製程式碼
2、Service
package com.example.demo.core.universal;
import org.apache.ibatis.exceptions.TooManyResultsException;
import tk.mybatis.mapper.entity.Condition;
import java.util.List;
/**
* @author 張瑤
* @Description: Service層基礎介面,其他Service介面請繼承該介面
* @date 2018/4/18 11:25
*/
public interface Service<T> {
/**
* @param model
* @Description: 持久化
* @Reutrn Integer
*/
Integer insert(T model);
/**
* @param id
* @Description: 通過主鍵刪除
* @Reutrn Integer
*/
Integer deleteById(String id);
/**
* @param ids
* @Description: 批量刪除 eg:ids -> “1,2,3,4”
* @Reutrn Integer
*/
Integer deleteByIds(String ids);
/**
* @param model
* @Description: 更新
* @Reutrn Integer
*/
Integer update(T model);
/**
* @param id
* @Description: 通過ID查詢
* @Reutrn T
*/
T selectById(String id);
/**
* @param fieldName
* @param value
* @throws TooManyResultsException
* @Description: 通過Model中某個成員變數名稱(非資料表中column的名稱)查詢,value需符合unique約束
* @Reutrn T
*/
T selectBy(String fieldName, Object value) throws TooManyResultsException;
/**
* @param fieldName javabean定義的屬性名,不是資料庫裡的屬性名
* @param value
* @Description: 通過Model中某個成員變數名稱(非資料表中column的名稱)查詢
* @Reutrn List<T>
*/
List<T> selectListBy(String fieldName, Object value);
/**
* @param ids
* @Description: 通過多個ID查詢//eg:ids -> “1,2,3,4”
* @Reutrn List<T>
*/
List<T> selectListByIds(String ids);
/**
* @param condition
* @Description: 根據條件查詢
* @Reutrn List<T>
*/
List<T> selectByCondition(Condition condition);
/**
* @Description: 獲取所有
* @Reutrn List<T>
*/
List<T> selectAll();
/**
* @param record
* @return List<T>
* @Description: 根據實體中的屬性值進行查詢,查詢條件使用等號
*/
List<T> select(T record);
/**
* @param record
* @return T
* @Description: 根據實體中的屬性值進行查詢,查詢條件使用等號
*/
T selectOne(T record);
}
複製程式碼
3、AbsratctService
package com.example.demo.core.universal;
import com.example.demo.core.ret.ServiceException;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Condition;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
/**
* @Description: 基於通用MyBatis Mapper外掛的Service介面的實現
* @author 張瑤
* @date 2018/4/18 11:28
*/
public abstract class AbstractService<T> implements Service<T> {
@Autowired
protected Mapper<T> mapper;
private Class<T> modelClass; // 當前泛型真實型別的Class
@SuppressWarnings("unchecked")
public AbstractService() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
@Override
public Integer insert(T model) {
return mapper.insertSelective(model);
}
@Override
public Integer deleteById(String id) {
return mapper.deleteByPrimaryKey(id);
}
@Override
public Integer deleteByIds(String ids) {
return mapper.deleteByIds(ids);
}
@Override
public Integer update(T model) {
return mapper.updateByPrimaryKeySelective(model);
}
@Override
public T selectById(String id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public T selectBy(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);
}
}
@Override
public List<T> selectListBy(String fieldName, Object value) {
try {
T model = modelClass.newInstance();
Field field = modelClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(model, value);
return mapper.select(model);
} catch (ReflectiveOperationException e) {
throw new ServiceException(e.getMessage(), e);
}
}
@Override
public List<T> selectListByIds(String ids) {
return mapper.selectByIds(ids);
}
@Override
public List<T> selectByCondition(Condition condition) {
return mapper.selectByCondition(condition);
}
@Override
public List<T> selectAll() {
return mapper.selectAll();
}
@Override
public List<T> select(T record){
return mapper.select(record);
}
@Override
public T selectOne(T recoed){
return mapper.selectOne(recoed);
}
}複製程式碼
五:新增mapper配置
在application.properties
中新增
mapper.mappers=com.example.demo.core.universal.Mapper複製程式碼
六:修改model,dao,service,serviceImpl,controller層程式碼
注意,之前user_info表主鍵為int型別,現修改為varchar;
注意,使用通用mapper需要在實體類的id加上@Id
1、UserInfo
package com.example.demo.model;
import javax.persistence.Column;
import javax.persistence.Id;
/**
* @author 張瑤
* @Description:
* @time 2018/4/18 11:55
*/
public class UserInfo {
/**
* 主鍵
*/
@Id
private String id;
/**
* 使用者名稱
*/
@Column(name = "user_name")
private String userName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
複製程式碼
2、UserInfoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserInfoMapper">
<resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">
<id column="id" jdbcType="VARCHAR" property="id"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
</resultMap>
<sql id="Base_Column_List">
id,user_name
</sql>
</mapper>複製程式碼
3、UserInfoMapper
package com.example.demo.dao;
import com.example.demo.core.universal.Mapper;
import com.example.demo.model.UserInfo;
/**
* @author 張瑤
* @Description:
* @time 2018/4/18 11:54
*/
public interface UserInfoMapper extends Mapper<UserInfo>{
}
複製程式碼
4、UserInfoService
package com.example.demo.service;
import com.example.demo.core.universal.Service;
import com.example.demo.model.UserInfo;
/**
* @author 張瑤
* @Description:
* @time 2018/4/18 11:56
*/
public interface UserInfoService extends Service<UserInfo>{
}
複製程式碼
5、UserInfoServiceImpl
package com.example.demo.service.impl;
import com.example.demo.core.universal.AbstractService;
import com.example.demo.core.ret.ServiceException;
import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author 張瑤
* @Description:
* @time 2018/4/18 11:56
*/
@Service
public class UserInfoServiceImpl extends AbstractService<UserInfo> implements UserInfoService{
@Resource
private UserInfoMapper userInfoMapper;
@Override
public UserInfo selectById(String id){
UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);
if(userInfo == null){
throw new ServiceException("暫無該使用者");
}
return userInfo;
}
}
複製程式碼
6、UserInfoController
package com.example.demo.controller;
import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @author 張瑤
* @Description:
* @time 2018/4/18 11:39
*/
@RestController
@RequestMapping("userInfo")
@Api(tags = {"使用者操作介面"}, description = "userInfoControler")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
@PostMapping("/hello")
public String hello() {
return "hello SpringBoot";
}
@ApiOperation(value = "查詢使用者", notes = "根據使用者ID查詢使用者")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "使用者ID", required = true,
dataType = "String", paramType = "query")
})
@PostMapping("/selectById")
public RetResult<UserInfo> selectById(@RequestParam String id) {
UserInfo userInfo = userInfoService.selectById(id);
return RetResponse.makeOKRsp(userInfo);
}
@PostMapping("/testException")
public RetResult<UserInfo> testException(String id) {
List a = null;
a.size();
UserInfo userInfo = userInfoService.selectById(id);
return RetResponse.makeOKRsp(userInfo);
}
@ApiOperation(value = "查詢使用者", notes = "分頁查詢使用者所有")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "當前頁碼",
dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "size", value = "每頁顯示條數",
dataType = "Integer", paramType = "query")
})
@PostMapping("/selectAll")
public RetResult<PageInfo<UserInfo>> selectAll(@RequestParam(defaultValue = "0") Integer page,
@RequestParam(defaultValue = "0") Integer size) {
PageHelper.startPage(page,size);
List<UserInfo> userInfoList = userInfoService.selectAll();
PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfoList);
return RetResponse.makeOKRsp(pageInfo);
}
}複製程式碼
七:功能測試
ok,在沒寫sql的情況下,功能依舊好使
專案地址
碼雲地址: gitee.com/beany/mySpr…
GitHub地址: github.com/MyBeany/myS…
寫文章不易,如對您有幫助,請幫忙點下star
結尾
整合通用 Mapper功能已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。