MyBatis 初级实战之二:增删改查,java 项目开发实战入门光盘
名为 curd 子工程,其 pom.xml 内容如下:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>curd</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>curd</name>
<description>Demo project for Mybatis CURD in Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
增加启动类,注意要用 MapperScan 注释来指定 mapper 接口代码的包路径:
package com.bolingcavalry.curd;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.bolingcavalry.curd.mapper")
public class CurdApplication {
public static void main(String[] args) {
SpringApplication.run(CurdApplication.class, args);
}
}
本次实战用到了 swagger,这样可以很方便的通过浏览器向各个 controller 接口发送请求,以下是配置类:
package com.bolingcavalry.curd;
import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return
new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.tags(new Tag("UserController", "用户服务"), new Tag("LogController", "日志服务"))
.select()
// 当前包路径
.apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.curd.controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api 文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("MyBatis CURD 操作")
//创建人
.contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
application.yml 内容如下:
server:
port: 8080
spring:
数据源
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.50.43:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis 配置
mybatis:
配置文件所在位置
config-location: classpath:mybatis-config.xml
映射文件所在位置
mapper-locations: classpath:mappers/*Mapper.xml
日志配置
logging:
level:
root: INFO
com:
bolingcavalry:
curd:
mapper: debug
增加 user 表的实体类 User.java,里面带有 swagger 的注解,方便在 swagger 页面展示:
package com.bolingcavalry.curd.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "用户实体类")
public class User {
@ApiModelProperty(value = "用户 ID")
private Integer id;
@ApiModelProperty(value = "用户名", required = true)
private String name;
@ApiModelProperty(value = "用户地址", required = false)
private Integer age;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
'}';
}
// 省去 get 和 set 方法,请您自行补齐
}
增加 log 表的实体类 Log.java,里面带有 swagger 的注解,方便在 swagger 页面展示:
package com.bolingcavalry.curd.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.sql.Date;
/**
@Description: 实体类
@author: willzhao E-mail: zq2599@gmail.com
@date: 2020/8/4 8:24
*/
@ApiModel(description = "日志实体类")
public class Log {
@ApiModelProperty(value = "日志 ID")
private Integer id;
@ApiModelProperty(value = "用户 ID")
private Integer userId;
@ApiModelProperty(value = "日志内容")
private String action;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@Override
public String toString() {
return "Log{" +
"id=" + id +
", userId=" + userId +
", action='" + action + ''' +
", createTime=" + createTime +
'}';
}
// 省去 get 和 set 方法,请您自行补齐
}
为联表查询的结果准备一个 bean,名为 LogExtend.java,继承自 Log.java,自己只有个 userName 字段,对应联表查询 user 表的 name 字段:
package com.bolingcavalry.curd.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "日志实体类(含用户表的字段)")
public class LogExtend extends Log {
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@ApiModelProperty(value = "用户名")
private String userName;
@Override
public String toString() {
return "LogExtend{" +
"id=" + getId() +
", userId=" + getUserId() +
", userName='" + getUserName() + ''' +
", action='" + getAction() + ''' +
", createTime=" + getCreateTime() +
'}';
}
}
增加 user 表的 mapper 映射文件,可见都是些很简单 sql,要注意的是批量新增的节点,这里面用到了 foreach 语法,可以通过集合动态生成 sql:
<?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.bolingcavalry.curd.mapper.UserMapper">
<select id="sel" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
<insert id="insertWithFields" useGeneratedKeys="true" keyProperty="id">
insert into user (id, name, age) values (#{id}, #{name}, #{age})
</insert>
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id">
insert into user (id, name, age)
values
<foreach collection="users" item="user" separator=",">
(#{user.id}, #{user.name}, #{user.age})
</foreach>
</insert>
<select id="findByName" parameterType="String" resultType="user">
select id, name, age from user where name like concat('%', #{name}, '%')
</select>
<delete id="delete">
delete from user where id= #{id}
</delete>
<delete id="clearAll">
delete from user
</delete>
<update id="update">
update user set name = #{name}, age = #{age} where id = #{id}
</update>
<select id="totalCount" resultType="java.lang.Integer">
select count(*) from user
</select>
</mapper>
增加 log 表的 mapper 映射文件,如下所示,请关注联表操作 selExtend,其结果是 logExtendResultMap:
<?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.bolingcavalry.curd.mapper.LogMapper">
<resultMap id="logExtendResultMap" type="logExtend">
<id property="id" column="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="action" jdbcType="VARCHAR" property="action"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="user_name" jdbcType="TIMESTAMP" property="userName"/>
</resultMap>
<insert id="insertWithFields" useGeneratedKeys="true" keyProperty="id" parameterType="log">
insert into log (id, user_id, action, create_time) values (#{id}, #{userId}, #{action}, #{createTime})
</insert>
<select id="selExtend" parameterType="int" resultMap="logExtendResultMap">
select l.id as id,
l.user_id as user_id,
l.action as action,
l.create_time as create_time,
u.name as user_name
from log as l
left join user as u
on l.user_id = u.id
where l.id = #{id}
</select>
</mapper>
增加用户表的 mapper 接口类 UserMapper.java ,对应着映射文件中的 sql 节点的 id:
package com.bolingcavalry.curd.mapper;
import com.bolingcavalry.curd.entity.LogExtend;
import com.bolingcavalry.curd.entity.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
User sel(int id);
int insertWithFields(User user);
int insertBatch(List<User> users);
int clearAll();
List<User> findByName(String name);
int update(User user);
int delete(int id);
int totalCount();
LogExtend selExtend(int id);
}
增加日志表的 mapper 接口类 LogMapper.java,对应着映射文件中的 sql 节点的 id:
package com.bolingcavalry.curd.mapper;
import com.bolingcavalry.curd.entity.Log;
import com.bolingcavalry.curd.entity.LogExtend;
import org.springframework.stereotype.Repository;
@Repository
public interface LogMapper {
Log sel(int id);
LogExtend selExtend(int id);
int insertWithFields(Log log);
}
mapper 接口完成后就是 service 层,先写 user 表的 service,如下所示,可见都是对 mapper 接口的调用:
package com.bolingcavalry.curd.service;
import com.bolingcavalry.curd.entity.User;
import com.bolingcavalry.curd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User sel(int id) {
return userMapper.sel(id);
}
public User insertWithFields(User user) {
userMapper.insertWithFields(user);
return user;
}
public List<User> insertBatch(List<User> users) {
userMapper.insertBatch(users);
return users;
}
public int clearAll() {
return userMapper.clearAll();
}
public List<User> findByName(String name) {
return userMapper.findByName(name);
}
public int update(User user) {
return userMapper.update(user);
}
public int delete(int id) {
return userMapper.delete(id);
}
public int totalCount() {
return userMapper.totalCount();
}
}
还有 log 表的 service:
package com.bolingcavalry.curd.service;
评论