今天给大家整理SpringBoot集成Mybatis用法笔记。希望对大家能有所帮助!
搭建一个SpringBoot基础项目。
具体可以参考SpringBoot:搭建第一个Web程序
引入相关依赖
<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.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>
准备数据库脚本
创建一个Mysql数据库,数据库名为test,然后执行一下脚本。
/*Navicat MySQL Data Transfer
Source Server : 本地MYSQLSource Server Version : 50644Source Host : localhost:3306Source Database : test
Target Server Type : MYSQLTarget Server Version : 50644File Encoding : 65001
Date: 2021-05-16 17:20:26*/
SET FOREIGN_KEY_CHECKS=0;
-- ------------------------------ Table structure for t_user-- ----------------------------DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) CHARACTER SET armscii8 DEFAULT NULL, `password` varchar(255) CHARACTER SET armscii8 DEFAULT NULL, `last_login_time` datetime DEFAULT NULL, `sex` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ------------------------------ Records of t_user-- ----------------------------INSERT INTO `t_user` VALUES ('1', 'xiaoxin', '123', '2019-07-27 16:01:21', '1');INSERT INTO `t_user` VALUES ('2', 'jack jo', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('4', 'landengdeng', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('5', 'max', '123', '2019-07-24 16:01:37', '1');INSERT INTO `t_user` VALUES ('6', 'liua11', '123456', null, '1');INSERT INTO `t_user` VALUES ('7', 'xiaozhang', '888888', null, '1');
配置项目配置文件 application.yml
server:port: 8090mybatis:configuration:map-underscore-to-camel-case: true mapper-locations: mybatis/**/*Mapper.xml
spring:datasource:driverClassName: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8username: rootpassword: rootlogging:level:my.springboot.mybatis.dao: debug
创建实体类 UserDO.java
package my.springboot.mybatis.entity;
import java.util.Date;
public class UserDO {private Integer id;private String userName;private String password;private Integer sex;private Date lastLoginTime;
public Integer getId() {return id; }
public void setId(Integer id) {this.id = id; }
public String getUserName() {return userName; }
public void setUserName(String userName) {this.userName = userName; }
public String getPassword() {return password; }
public void setPassword(String password) {this.password = password; }
public Integer getSex() {return sex; }
public void setSex(Integer sex) {this.sex = sex; }
public Date getLastLoginTime() {return lastLoginTime; }
public void setLastLoginTime(Date lastLoginTime) {this.lastLoginTime = lastLoginTime; }
@Override public String toString() {return "UserDO{" +"id=" + id +", userName='" + userName + '\'' +", password='" + password + '\'' +", sex=" + sex +", lastLoginTime=" + lastLoginTime +'}'; }}
创建mapper文件 UserInfoMapper.java
package my.springboot.mybatis.dao;
import java.util.List;import java.util.Map;import my.springboot.mybatis.entity.UserDO;import org.apache.ibatis.annotations.Mapper;
@Mapperpublic interface UserInfoMapper { UserDO get(Integer id); List<UserDO> list(Map<String, Object> map);int count(Map<String, Object> map);int save(UserDO user);int update(UserDO user);int remove(Integer id);int batchRemove(Integer[] ids);}
创建Mapper映射文件 UserInfoMapper.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="my.springboot.mybatis.dao.UserInfoMapper"><select id="get" resultType="my.springboot.mybatis.entity.UserDO"> select id,user_name,password,last_login_time,sex from t_user where id = #{value}</select><select id="list" resultType="my.springboot.mybatis.entity.UserDO"> select id,user_name,password,last_login_time,sex from t_user<where><if test="id != null and id != '-1' " > and id = #{id} </if><if test="userName != null and userName != '' " > and user_name = #{userName} </if><if test="password != null and password != '' " > and password = #{password} </if><if test="lastLoginTime != null and lastLoginTime != '' " > and last_login_time = #{lastLoginTime} </if><if test="sex != null and sex != '-1' " > and sex = #{sex} </if></where><choose><when test="sort != null and sort.trim() != ''"> order by ${sort} ${order}</when><otherwise> order by id desc</otherwise></choose><if test="offset != null and limit != null"> limit #{offset}, #{limit}</if></select><select id="count" resultType="int"> select count(*) from t_user<where><if test="id != null and id != '-1' " > and id = #{id} </if><if test="userName != null and userName != '' " > and user_name = #{userName} </if><if test="password != null and password != '' " > and password = #{password} </if><if test="lastLoginTime != null and lastLoginTime != '' " > and last_login_time = #{lastLoginTime} </if><if test="sex != null and sex != '-1' " > and sex = #{sex} </if></where></select><insert id="save" parameterType="my.springboot.mybatis.entity.UserDO" useGeneratedKeys="true" keyProperty="id"> insert into t_user ( user_name, password, last_login_time, sex) values ( #{userName}, #{password}, #{lastLoginTime}, #{sex})</insert><update id="update" parameterType="my.springboot.mybatis.entity.UserDO"> update t_user<set><if test="userName != null">user_name = #{userName}, </if><if test="password != null">password = #{password}, </if><if test="lastLoginTime != null">last_login_time = #{lastLoginTime}, </if><if test="sex != null">sex = #{sex}</if></set> where id = #{id}</update><delete id="remove"> delete from t_user where id = #{value}</delete>
<delete id="batchRemove"> delete from t_user where id in<foreach item="id" collection="array" open="(" separator="," close=")"> #{id}</foreach></delete></mapper>
创建服务接口 IUserInfoService.java
package my.springboot.mybatis.service;import my.springboot.mybatis.entity.UserDO;
import java.util.List;
public interface IUserInfoService { List<UserDO> findAll();UserDO findById(Integer id);
void insert(UserDO model);Integer update(UserDO model);Integer deleteById(Integer id);
}
创建服务实现类 UserInfoService.java
package my.springboot.mybatis.service.impl;import my.springboot.mybatis.dao.UserInfoMapper;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.service.IUserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
import java.util.List;@Servicepublic class UserInfoService implements IUserInfoService {@Autowired private UserInfoMapper mapper;@Override public List<UserDO> findAll() {return mapper.list(null); }
@Override public UserDO findById(Integer id) {return mapper.get(id); }
@Override public void insert(UserDO model) {mapper.save(model); }
@Override public Integer update(UserDO model) {return mapper.update(model); }
@Override public Integer deleteById(Integer id) {return mapper.remove(id); }}
创建控制器 HomeController.java
package my.springboot.mybatis.controller;import my.springboot.mybatis.entity.UserDO;import my.springboot.mybatis.service.IUserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;
import javax.jws.soap.SOAPBinding;import java.util.Date;@Controllerpublic class HomeController {@Autowired private IUserInfoService userInfoService;@RequestMapping("index") //注解映射请求路径 @ResponseBody //可以将java对象转为json格式的数据 public String index() { UserDO user=userInfoService.findById(1);// 新增用户 UserDO add=new UserDO(); add.setSex(1); add.setUserName("xiaozhang"); add.setPassword("888888"); add.setLastLoginTime(null);//userInfoService.insert(add); // 更新用户 user.setUserName("xiaoxin");//userInfoService.update(user); // 删除用户 userInfoService.deleteById(3);
return "Hello World !"; }}
启动地址:http://localhost:8090/index
项目结构文件截图