Hello你們好,本章咱們集成通用 Mapper功能 。有問題能夠聯繫我mr_beany@163.com。另求各路大神指點,感謝
通用 Mapper 是一個能夠實現任意 MyBatis 通用方法的框架,項目提供了常規的增刪改查操做以及Example
相關的單表操做。通用 Mapper 是爲了解決 MyBatis 使用中 90% 的基本操做,使用它能夠很方便的進行開發,能夠節省開發人員大量的時間。java
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>複製代碼
這裏咱們從新配置MapperScannerConfigurergit
打開MybatisConfigurer
github
將import org.mybatis.spring.mapper.MapperScannerConfigurer;修改成web
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
spring
建立core→universal文件夾sql
建立如下文件數據庫
一、Mapperapache
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> {
}
複製代碼
二、Servicebash
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);
}
複製代碼
三、AbsratctServicemybatis
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);
}
}複製代碼
在application.properties
中添加
mapper.mappers=com.example.demo.core.universal.Mapper複製代碼
注意,以前user_info表主鍵爲int類型,現修改成varchar;
注意,使用通用mapper須要在實體類的id加上@Id
一、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;
}
}
複製代碼
二、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>複製代碼
三、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>{
}
複製代碼
四、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>{
}
複製代碼
五、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;
}
}
複製代碼
六、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。另求各路大神指點,感謝你們。