因时间有限,简单说明一下 springboot 如何集成 mybatis的。详细的代码库地址:
https://gitee.com/leo825/springboot-learning-parents.git
本地开发使用 jdk8,mysql 版本 8.0.28
<?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">
<parent>
<groupId>org.example</groupId>
<artifactId>springboot-learning-parents</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>springboot-demo</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>springboot-mybatis</name>
<description>springboot 集成 mybatis</description>
<packaging>jar</packaging>
<url>https://gitee.com/leo825/springboot-learning-parents.git</url>
<properties>
<start-class>com.demo.SpringbootMybatisApplication</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatis.version>1.3.2</mybatis.version>
<mysql.version>8.0.28</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 集成 mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
springboot 配置文件配置如下:
# springboot多环境配置
#端口,项目上下文
server:
port: 8080
servlet:
context-path: /springboot-mybatis
spring:
# mysql 数据库连接信息,本地使用 mysql 服务版本为:8.0.28
datasource:
username: root
password: 6tojyh*A3eQ6
url: jdbc:mysql://localhost:3306/local_test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis 配置
mybatis:
type-aliases-package: com.demo.model
mapper-locations: classpath:mapper/*.xml
# 日志输出配置
logging:
level:
root: INFO
org:
springframework:
security: WARN
web: ERROR
# 设置自己的 mapper 目录 输出sql日志
com.demo.mapper: debug
file:
path: ./logs
name: './logs/springboot-mybatis.log'
pattern:
file: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
console: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
使用 @MapperScan 注解,添加 Mapper
package com.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value = "com.demo.mapper")
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
create table t_user (
id int (10) primary key auto_increment comment '用户主键',
username varchar (100) not null comment '用户名称',
pwd varchar(50) not null comment '密码',
create_time datetime not null comment '创建时间',
update_time datetime comment '修改时间'
) engine = innodb default charset = utf8 collate = utf8_bin comment '用户表';
package com.demo.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
Integer id;
String userName;
String pwd;
Date createTime;
Date updateTime;
}
package com.demo.mapper;
import com.demo.model.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
/**
* 新增
* @param user
*/
void addUser(User user);
/**
* 删除用户
* @param id
*/
void deleteUserById(Integer id);
/**
* 更新用户
* @param user
* @return
*/
void updateUser(User user);
/**
* 查询用户
* @param ids
* @return
*/
List<User> getUsersById(List<Integer> ids);
}
mapper.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">
<!-- namespace:填写映射当前的Mapper接口,所有的增删改查的参数和返回值类型,
就可以直接填写缩写,不区分大小写,直接通过方法名去找类型-->
<mapper namespace="com.demo.mapper.UserMapper">
<!-- 封装映射关系,数据库中的字段和实体类之间的映射关系-->
<resultMap type="com.demo.model.User" id="userMap">
<!-- 指定主键列的封装规则:与下面<result>标签的区别是可以用于提升性能,所以这里用<id>标签来定义主键的映射关系
column:数据库中对应的字段名
property:对应JavaBean 的属性名
-->
<id column="id" property="id"></id>
<!-- 定义普通列封装规则-->
<result column="username" property="userName"></result>
<!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
<result column="pwd" property="pwd"></result>
<result column="create_time" property="createTime"></result>
<result column="update_time" property="updateTime"></result>
</resultMap>
<!-- sql:里面可以写入一个共同的sql代码,用于提取重复的代码。
要使用该代码的时候就直接使用<include>标签
id:为提取的sql代码,取一个id,起标识作用
-->
<sql id="select">
select * from t_user
</sql>
<!-- public void addUser(User user);
insert:用于执行添加语句;update:执行更新语句
同样 delete:执行删除语句
-->
<insert id="addUser" parameterType="com.demo.model.User">
<!-- selectKey配置主键信息的标签
keyColumn:对应数据库表中的主键列
keyProperty:对应实体类中的属性
after:代表执行下面代码之前,先执行当前里面的代码
-->
<selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into t_user
(id,username,pwd,create_time,update_time)
values(#{id},#{userName},#{pwd},#{createTime},#{updateTime})
</insert>
<!-- 如果字段非空就更新 -->
<update id="updateUser" parameterType="com.demo.model.User">
update t_user
<set >
<if test="userName != null">
username = #{userName},
</if>
<if test="pwd != null">
pwd = #{pwd},
</if>
update_time = #{updateTime}
</set>
where id = #{id}
</update>
<!-- 根据id删除 -->
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from t_user where id = #{id}
</delete>
<!-- QueryVo:是一个实体包装类,通常用于封装实体类之外的一些属性-->
<select id="getUsersById" parameterType="java.util.List" resultMap="userMap">
<include refid="select"></include>
<where>
<!-- foreach:循环语句,通常多用于参数是集合时,需要对参数进行遍历出来,再进行赋值查询
collection:参数类型中的集合、数组的名字,例:下面的ids就是QueryVo这个类中的list集合的名字
item:为遍历该集合起一个变量名,遍历出来的每一个字,都赋值到这个item中
open:在sql语句前面添加的sql片段
close:在sql语句后面添加的sql片段
separator:指定遍历元素之前用什么分隔符
-->
<foreach collection="list" item="id" open="id in(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
package com.demo.service;
import com.demo.model.User;
import java.util.List;
public interface UserService {
/**
* 新增
* @param user
*/
void addUser(User user);
/**
* 删除用户
* @param id
*/
void deleteUserById(Integer id);
/**
* 更新用户
* @param user
* @return
*/
void updateUser(User user);
/**
* 查询用户
* @param ids
* @return
*/
List<User> getUsersById(List<Integer> ids);
}
impl 实现类
package com.demo.service.impl;
import com.demo.mapper.UserMapper;
import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.addUser(user);
}
@Override
public void deleteUserById(Integer id) {
userMapper.deleteUserById(id);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public List<User> getUsersById(List<Integer> ids) {
return userMapper.getUsersById(ids);
}
}
package com.demo.controller;
import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.server.InactiveGroupException;
import javax.annotation.Resource;
import java.util.*;
@RestController
public class UserController {
@Resource
UserService userService;
/**
* 新增数据示例
*
* @param username
* @param password
* @return
*/
@RequestMapping("/add")
private String getUserById(String username,String password){
User user = new User();
user.setUserName(username);
user.setPwd(password);
user.setCreateTime(new Date());
userService.addUser(user);
return "success";
}
/**
* 根据id删除数据
*
* @param userId
* @return
*/
@RequestMapping("/delete")
private String deleteUserById(String userId){
Integer id = Integer.parseInt(userId);
userService.deleteUserById(id);
return "success";
}
/**
* 修改用户数据的时候必须知道用户的id
*
* @param id
* @param username
* @param password
* @return
*/
@RequestMapping("/update")
private String updateUser(String id, String username,String password){
User user = new User();
user.setId(Integer.parseInt(id));
user.setUserName(username);
user.setPwd(password);
user.setUpdateTime(new Date());
userService.updateUser(user);
return "success";
}
/**
* 根据id删除数据
*
* @param userId
* @return
*/
@RequestMapping("/getUserList")
private String getUsersById(String userId){
String[] idsStr = userId.split(",");
List<Integer> ids = new ArrayList<>();
for(String str : idsStr){
ids.add(Integer.parseInt(str));
}
List<User> users = userService.getUsersById(ids);
return users.toString();
}
}
通过 controller 可以进行新增、修改、查询、删除等操作了。