本章介绍 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
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("com.hogwartsmini.demo.dao")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;
@Repositorypublic interface HogwartsTestUserMapper extends MySqlExtensionMapper<HogwartsTestUser> {
}
复制代码
Service 层中使用
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 '主键', `user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', `password` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '密码', `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '邮箱', `auto_create_case_job_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '自动生成用例job名称 不为空时表示已经创建job', `start_test_job_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '执行测试job名称 不为空时表示已经创建job', `default_jenkins_id` int DEFAULT NULL COMMENT '默认Jenkins服务器', `create_time` datetime NOT NULL COMMENT '创建时间', `update_time` datetime NOT NULL COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT='用户表';
复制代码
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 = "霍格沃兹测试学院-用户管理模块")@RestController@RequestMapping("hogwartsUser")public class HogwartsTestUserDbController {
@Autowired private HogwartsTestUserService hogwartsTestUserService;
@ApiOperation("用户注册") @PostMapping("register") public HogwartsTestUser register( @RequestBody HogwartsTestUser hogwartsTestUser){ return hogwartsTestUserService.save(hogwartsTestUser); }
@ApiOperation("用户信息修改接口") @PutMapping() public HogwartsTestUser updateUserInfo( @RequestBody HogwartsTestUser hogwartsTestUser){ return hogwartsTestUserService.update(hogwartsTestUser); }
@ApiOperation("根据用户id删除用户信息") @DeleteMapping("{userId}") public Integer delete(@PathVariable("userId") Integer userId){ return hogwartsTestUserService.delete(userId); }
@ApiOperation("根据用户名查询") @GetMapping("byName") public List<HogwartsTestUser> getByName( @RequestParam("userName") 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 **/@Servicepublic 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
请求参数
{ "userName": "霍格沃兹test123", "password": "test123"}
复制代码
响应参数
{ "id": 15, "userName": "霍格沃兹test123", "password": "test123", "email": null, "autoCreateCaseJobName": null, "startTestJobName": null, "defaultJenkinsId": null, "createTime": "2021-04-14T09:37:58.358+00:00", "updateTime": "2021-04-14T09:37:58.358+00:00"}
复制代码
GET http://127.0.0.1:8081/hogwartsUser/byName?userName=%E9%9C%8D%E6%A0%BC%E6%B2%83%E5%85%B9test123
请求参数
见请求地址中 userName =霍格沃兹test123
复制代码
响应参数
[ { "id": 15, "userName": "霍格沃兹test123", "password": "test123", "email": null, "autoCreateCaseJobName": null, "startTestJobName": null, "defaultJenkinsId": null, "createTime": "2021-04-14T09:37:58.000+00:00", "updateTime": "2021-04-14T09:37:58.000+00:00" }]
复制代码
PUT http://127.0.0.1:8081/hogwartsUser
请求参数
{ "id": 15, "userName": "霍格沃兹test12345", "password": "test123"}
复制代码
响应参数
{ "id": 15, "userName": "霍格沃兹test12345", "password": "test123", "email": null, "autoCreateCaseJobName": null, "startTestJobName": null, "defaultJenkinsId": null, "createTime": "2021-04-14T09:43:45.018+00:00", "updateTime": "2021-04-14T09:43:45.018+00:00"}
复制代码
DELETE http://127.0.0.1:8081/hogwartsUser
请求参数
响应参数
数据持久化技术就先讲到这里啦~大家要多练习哦,才能学的更扎实。
评论