|
本文节选自霍格沃兹测试学院内部教材 本章介绍 Web 后端开发中数据持久化技术 TKMyBatis。
TKMyBatis简介
TKMybatis 是基于 Mybatis 框架开发的一个工具,内部实现了对单表的基本数据操作,只需要简单继承 TKMybatis 提供的接口,就能够实现无需编写任何 sql 即能完成单表操作。
下面简单介绍下 MyBatis , MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
详细内容请参考 https://mybatis.org/mybatis-3/zh/index.html 2
TKMyBatis快速开始
Maven依赖
<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</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>在启动类中配置 MapperScan 扫描
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(&#34;com.hogwartsmini.demo.dao&#34;)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}实体类中使用
在实体类中,常用的注解和意义为:
Table:描述数据库表信息,主要属性有 name(表名)、schema、catalog、uniqueConstraints 等。
Id:指定表主键字段,没有属性值。
Column:描述数据库字段信息,主要属性有 name(字段名)、columnDefinition、insertable、length、nullable(是否可为空)、precision、scale、table、unique、updatable 等。
ColumnType:描述数据库字段类型,可对一些特殊类型作配置,进行特殊处理,主要属性有 jdbcType、column、typeHandler 等。
dao 中使用
首先创建一个公共接口,继承 Mapper, MySqlMapper, IdsMapper 三个类,用于后续业务 Mapper 接口直接实现。
import tk.mybatis.mapper.common.IdsMapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MySqlExtensionMapper<T> extends Mapper<T>, MySqlMapper<T>, IdsMapper<T> {
}
创建 HogwartsTestUserMapper.java 接口
import com.hogwartsmini.demo.common.MySqlExtensionMapper;
import com.hogwartsmini.demo.entity.HogwartsTestUser;
import org.springframework.stereotype.Repository;
@Repository
public interface HogwartsTestUserMapper extends MySqlExtensionMapper<HogwartsTestUser> {
}Service 层中使用
类型 | 说明 | Mapper.insert(record) | 保存一个实体,null 的属性也会保存,不会使用数据库默认值 | Mapper.insertSelective(record) | 保存一个实体,忽略空值,即没提交的值会使用使用数据库默认值 | Mapper.insertUseGeneratedKeys(record) | 保存一个实体,会自动填入在数据库中生成的 id 值。注意使用此方法插入数据时,如果 id 字段不是 AUTO_INCREMENT ,则不会生成新的 id |
类型 | 说明 | Mapper.delete(record) | 根据实体属性作为条件进行删除,查询条件使用等号 | Mapper.deleteByExample(example) | 根据 Example 条件删除数据 | Mapper.deleteByPrimaryKey(key) | 根据主键字段进行删除,方法参数必须包含完整的主键属性 |
类型 | 说明 | Mapper.updateByExample(record,example) | 根据 Example 条件更新实体record 包含的全部属性,null 值会被更新 | Mapper.updateByExampleSelective(record, example) | 根据 Example 条件更新实体record 包含的不是 null 的属性值 | Mapper.updateByPrimaryKey(record) | 根据主键更新实体全部字段,null 值会被更新 | Mapper.updateByPrimaryKeySelective(record) | 根据主键更新属性不为 null 的值 |
类型 | 说明 | Mapper.select(record) | 根据实体中的属性值进行查询,查询条件使用等号 | Mapper.selectAll() | 查询全部结果 | Mapper.selectByExample(example) | 根据 Example 条件进行查询 | Mapper.selectByPrimaryKey(key) | 根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号 | Mapper.selectCount(record) | 根据实体中的属性查询总数,查询条件使用等号 | Mapper.selectCountByExample(example) | 根据 Example 条件进行查询总数 | Mapper.selectByExample(example) | 根据 Example 条件进行查询 | Mapper.selectOne(record) | 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号。但是如果存在某个属性为 int,则会初始化为 0。可能影响到实际使用 |
Spring Boot 配置文件
spring:
application:
name: aitest
#数据库配置信息
datasource:
url: jdbc:mysql://localhost:3306/aitest_mini?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: hogwarts
password: db@hogwarts
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.hogwartstest.aitestmini.entity
configuration:
mapUnderscoreToCamelCase: true
logging:
level:
com.hogwartstest.aitestmini.dao: debug #打印sql示例表结构
CREATE TABLE `hogwarts_test_user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT &#39;主键&#39;,
`user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT &#39;用户名&#39;,
`password` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT &#39;密码&#39;,
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT &#39;邮箱&#39;,
`auto_create_case_job_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT &#39;自动生成用例job名称 不为空时表示已经创建job&#39;,
`start_test_job_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT &#39;执行测试job名称 不为空时表示已经创建job&#39;,
`default_jenkins_id` int DEFAULT NULL COMMENT &#39;默认Jenkins服务器&#39;,
`create_time` datetime NOT NULL COMMENT &#39;创建时间&#39;,
`update_time` datetime NOT NULL COMMENT &#39;更新时间&#39;,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT=&#39;用户表&#39;;Controller 代码
import com.hogwartsmini.demo.entity.HogwartsTestUser;
import com.hogwartsmini.demo.service.HogwartsTestUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Author tlibn
* @Date 2020/7/16 17:14
**/
@Api(tags = &#34;霍格沃兹测试学院-用户管理模块&#34;)
@RestController
@RequestMapping(&#34;hogwartsUser&#34;)
public class HogwartsTestUserDbController {
@Autowired
private HogwartsTestUserService hogwartsTestUserService;
@ApiOperation(&#34;用户注册&#34;)
@PostMapping(&#34;register&#34;)
public HogwartsTestUser register(
@RequestBody HogwartsTestUser hogwartsTestUser){
return hogwartsTestUserService.save(hogwartsTestUser);
}
@ApiOperation(&#34;用户信息修改接口&#34;)
@PutMapping()
public HogwartsTestUser updateUserInfo(
@RequestBody HogwartsTestUser hogwartsTestUser){
return hogwartsTestUserService.update(hogwartsTestUser);
}
@ApiOperation(&#34;根据用户id删除用户信息&#34;)
@DeleteMapping(&#34;{userId}&#34;)
public Integer delete(@PathVariable(&#34;userId&#34;) Integer userId){
return hogwartsTestUserService.delete(userId);
}
@ApiOperation(&#34;根据用户名查询&#34;)
@GetMapping(&#34;byName&#34;)
public List<HogwartsTestUser> getByName(
@RequestParam(&#34;userName&#34;) String userName){
HogwartsTestUser hogwartsTestUser = new HogwartsTestUser();
hogwartsTestUser.setUserName(userName);
return hogwartsTestUserService.getByName(hogwartsTestUser);
}HogwartsTestUserService 代码
import com.hogwartsmini.demo.entity.HogwartsTestUser;
import java.util.List;
public interface HogwartsTestUserService {
/**
* 保存
* @param hogwartsTestUser
* @return
*/
HogwartsTestUser save(HogwartsTestUser hogwartsTestUser);
/**
* 更新
* @param hogwartsTestUser
* @return
*/
HogwartsTestUser update(HogwartsTestUser hogwartsTestUser);
/**
* 根据用户名查询
* @param hogwartsTestUser
* @return
*/
List<HogwartsTestUser> getByName(HogwartsTestUser hogwartsTestUser);
/**
* 根据用户id删除用户信息
* @param userId
* @return
*/
Integer delete(Integer userId);
}HogwartsTestUserServiceImpl 代码
import com.hogwartsmini.demo.dao.HogwartsTestUserMapper;
import com.hogwartsmini.demo.entity.HogwartsTestUser;
import com.hogwartsmini.demo.service.HogwartsTestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @Author tlibn
* @Date 2020/7/17 11:03
**/
@Service
public class HogwartsTestUserServiceImpl implements HogwartsTestUserService {
@Autowired
private HogwartsTestUserMapper hogwartsTestUserMapper;
/**
* 保存
*
* @param hogwartsTestUser
* @return
*/
@Override
public HogwartsTestUser save(HogwartsTestUser hogwartsTestUser) {
hogwartsTestUser.setCreateTime(new Date());
hogwartsTestUser.setUpdateTime(new Date());
hogwartsTestUserMapper.insertUseGeneratedKeys(hogwartsTestUser);
return hogwartsTestUser;
}
/**
* 更新
*
* @param hogwartsTestUser
* @return
*/
@Override
public HogwartsTestUser update(HogwartsTestUser hogwartsTestUser) {
hogwartsTestUser.setCreateTime(new Date());
hogwartsTestUser.setUpdateTime(new Date());
hogwartsTestUserMapper.updateByPrimaryKeySelective(hogwartsTestUser);
return hogwartsTestUser;
}
/**
* 根据用户名查询
*
* @param hogwartsTestUser
* @return
*/
@Override
public List<HogwartsTestUser> getByName(HogwartsTestUser hogwartsTestUser) {
List<HogwartsTestUser> hogwartsTestUserList = hogwartsTestUserMapper.select(hogwartsTestUser);
return hogwartsTestUserList;
}
/**
* 根据用户id删除用户信息
*
* @param userId
* @return
*/
@Override
public Integer delete(Integer userId) {
HogwartsTestUser hogwartsTestUser = new HogwartsTestUser();
hogwartsTestUser.setId(userId);
hogwartsTestUserMapper.delete(hogwartsTestUser);
return userId;
}
}使用 Postman 测试增删改查
POST http://127.0.0.1:8081/hogwartsUser/register
请求参数
{
&#34;userName&#34;: &#34;霍格沃兹test123&#34;,
&#34;password&#34;: &#34;test123&#34;
}响应参数
{
&#34;id&#34;: 15,
&#34;userName&#34;: &#34;霍格沃兹test123&#34;,
&#34;password&#34;: &#34;test123&#34;,
&#34;email&#34;: null,
&#34;autoCreateCaseJobName&#34;: null,
&#34;startTestJobName&#34;: null,
&#34;defaultJenkinsId&#34;: null,
&#34;createTime&#34;: &#34;2021-04-14T09:37:58.358+00:00&#34;,
&#34;updateTime&#34;: &#34;2021-04-14T09:37:58.358+00:00&#34;
}
GET http://127.0.0.1:8081/hogwartsUser/byName?userName=霍格沃兹test123
请求参数
见请求地址中 userName =霍格沃兹test123响应参数
[
{
&#34;id&#34;: 15,
&#34;userName&#34;: &#34;霍格沃兹test123&#34;,
&#34;password&#34;: &#34;test123&#34;,
&#34;email&#34;: null,
&#34;autoCreateCaseJobName&#34;: null,
&#34;startTestJobName&#34;: null,
&#34;defaultJenkinsId&#34;: null,
&#34;createTime&#34;: &#34;2021-04-14T09:37:58.000+00:00&#34;,
&#34;updateTime&#34;: &#34;2021-04-14T09:37:58.000+00:00&#34;
}
]
PUT http://127.0.0.1:8081/hogwartsUser
请求参数
{
&#34;id&#34;: 15,
&#34;userName&#34;: &#34;霍格沃兹test12345&#34;,
&#34;password&#34;: &#34;test123&#34;
}响应参数
{
&#34;id&#34;: 15,
&#34;userName&#34;: &#34;霍格沃兹test12345&#34;,
&#34;password&#34;: &#34;test123&#34;,
&#34;email&#34;: null,
&#34;autoCreateCaseJobName&#34;: null,
&#34;startTestJobName&#34;: null,
&#34;defaultJenkinsId&#34;: null,
&#34;createTime&#34;: &#34;2021-04-14T09:43:45.018+00:00&#34;,
&#34;updateTime&#34;: &#34;2021-04-14T09:43:45.018+00:00&#34;
}
DELETE http://127.0.0.1:8081/hogwartsUser/15
请求参数
见请求地址中15响应参数
15数据持久化技术就先讲到这里啦~大家要多练习哦,才能学的更扎实。 |
|