使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删改查SQL。而且,当数据库表结构改动时,对应的所有SQL以及实体类都需要更改。这工作量和效率的影响或许就是区别增删改查程序员和真正程序员的屏障。这时,通用Mapper便应运而生。
通用Mapper就是为了解决单表增删改查,基于Mybatis的插件。开发人员不需要编写SQL,不需要在DAO中增加方法,只要写好实体类,就能支持相应的增删改查方法。
通用Mapper实例:
代码工程结构:
数据库使用mysql,建表语句:
CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`userName` varchar(32) NOT NULL,
`passWord` varchar(50) NOT NULL,
`realName` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
maven依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.mybatis</groupId>
<artifactId>mybatisdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisdemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置:
server:
port: 8090
spring:
datasource:
username: root
password: Yj_123456
url: jdbc:mysql://192.168.0.106:3306/alpha?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.demo.mybatis.entity
mapper:
mappers: com.demo.mybatis.basemapper.MyMapper
identity: MYSQL
#showSql
logging:
level:
com:
example:
mapper : debug
mapper配置xml文档内容(UserMapping.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.demo.mybatis.mapper.UserMapper">
<select id="sel" resultType="User">
select id,userName,passWord,realName from user where id = #{id}
</select>
</mapper>
实体类:
package com.demo.mybatis.entity;
import lombok.Data;
import javax.persistence.*;
@Table(name = "user")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "userName")
private String userName;
@Column(name = "passWord")
private String passWord;
@Column(name = "realName")
private String realName;
}
常亮接口:
package com.demo.mybatis.constant;
public interface CommonConstant {
String STATUS_OK = "success";
String STATUS_FAIL = "fail";
}
通用Mapper接口:
package com.demo.mybatis.basemapper;
import tk.mybatis.mapper.additional.idlist.IdListMapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends IdListMapper<T, Long>, Mapper<T>, MySqlMapper<T> {
}
业务Mapper接口:
package com.demo.mybatis.mapper;
import com.demo.mybatis.basemapper.MyMapper;
import com.demo.mybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends MyMapper<User> {
}
通用结果VO:
package com.demo.mybatis.vo;
import lombok.Data;
@Data
public class GenericResult<T> {
private String code;
private String message;
private T data;
}
结果处理工具类:
package com.demo.mybatis.util;
import com.demo.mybatis.constant.CommonConstant;
import com.demo.mybatis.vo.GenericResult;
import org.springframework.stereotype.Service;
@Service
public class ResultUtil<T> {
public GenericResult<T> success(T data) {
GenericResult<T> result = new GenericResult();
result.setData(data);
result.setCode(CommonConstant.STATUS_OK);
return result;
}
}
业务Service类:
package com.demo.mybatis.service;
import com.demo.mybatis.constant.CommonConstant;
import com.demo.mybatis.entity.User;
import com.demo.mybatis.mapper.UserMapper;
import com.demo.mybatis.vo.GenericResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User selectOne(int id) {
User user = new User();
user.setId(id);
return userMapper.selectOne(user);
}
public void save(List<User> users) {
userMapper.insertList(users);
}
public void save(User user) {
userMapper.insert(user);
}
public void update(User user) {
userMapper.updateByPrimaryKey(user);
}
public List<User> getAll() {
return userMapper.selectAll();
}
public GenericResult<PageInfo<User>> page(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.selectAll();
PageInfo<User> pageInfo = new PageInfo<User>(users);
GenericResult<PageInfo<User>> result = new GenericResult<>();
result.setCode(CommonConstant.STATUS_OK);
result.setMessage("ok");
result.setData(pageInfo);
return result;
}
}
业务Controller类:
package com.demo.mybatis.controller;
import com.demo.mybatis.entity.User;
import com.demo.mybatis.util.ResultUtil;
import com.demo.mybatis.vo.GenericResult;
import com.demo.mybatis.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/demo/mybatis")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private ResultUtil<String> resultUtil;
@RequestMapping("getUser/{id}")
public User getUser(@PathVariable int id) {
return userService.selectOne(id);
}
@RequestMapping("getAllUser")
public List<User> getAllUser() {
return userService.getAll();
}
@PostMapping("saveOne")
public GenericResult<String> saveOne(@RequestBody User user) {
userService.save(user);
return resultUtil.success(user.getUserName());
}
@PostMapping("saveList")
public GenericResult<String> saveList(@RequestBody List<User> users) {
userService.save(users);
return resultUtil.success(users.size() + "");
}
@PutMapping("update")
public GenericResult<String> update(@RequestBody User user) {
userService.update(user);
return resultUtil.success("success");
}
@RequestMapping("page")
public GenericResult<PageInfo<User>> page(@RequestParam(name = "pageNum") int pageNum, @RequestParam(name = "pageSize") int pageSize) {
return userService.page(pageNum, pageSize);
}
}
DAO
的写法
在传统的Mybatis写法中,DAO
接口需要与Mapper
文件关联,即需要编写SQL
来实现DAO
接口中的方法。而在通用Mapper中,DAO
只需要继承一个通用接口,即可拥有丰富的方法:
继承通用的Mapper,必须指定泛型
一旦继承了Mapper,继承的Mapper就拥有了Mapper所有的通用方法:
public interface MyMapper<T> extends IdListMapper<T, Long>, Mapper<T>, MySqlMapper<T> { }
Select
方法:List<T> select(T record);
说明:根据实体中的属性值进行查询,查询条件使用等号
方法:T selectByPrimaryKey(Object key);
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
方法:List<T> selectAll();
说明:查询全部结果,select(null)方法能达到同样的效果
方法:T selectOne(T record);
说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
方法:int selectCount(T record);
说明:根据实体中的属性查询总数,查询条件使用等号
Insert
方法:int insert(T record);
说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
方法:int insertSelective(T record);
说明:保存一个实体,null的属性不会保存,会使用数据库默认值
Update
方法:int updateByPrimaryKey(T record);
说明:根据主键更新实体全部字段,null值会被更新
方法:int updateByPrimaryKeySelective(T record);
说明:根据主键更新属性不为null的值
Delete
方法:int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号
方法:int deleteByPrimaryKey(Object key);
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
Example方法
方法:List<T> selectByExample(Object example);
说明:根据Example条件进行查询
重点:这个查询支持通过Example
类指定查询列,通过selectProperties
方法指定查询列
方法:int selectCountByExample(Object example);
说明:根据Example条件进行查询总数
方法:int updateByExample(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record
包含的全部属性,null值会被更新
方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record
包含的不是null的属性值
方法:int deleteByExample(Object example);
说明:根据Example条件删除数据
总结
通用Mapper的原理是通过反射获取实体类的信息,构造出相应的SQL,因此我们只需要维护好实体类即可,对于应付复杂多变的需求提供了很大的便利。上文叙述的只是通用Mapper的简单用法,在实际项目中,还是要根据业务,在通用Mapper的基础上封装出粒度更大、更通用、更好用的方法。