Bootstrap

Springboot + Mybatis实现增删改查

1.创建数据库:

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT COMMENT 'id',
  `username` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名',
  `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '密码',
  `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '性别1代表男2代表女',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

2.创建Springboot项目

3.创建包 entity,controller,service,entity,mapper

4.配置application.yml

mybatis:
  type-aliases-package: com.xiaoli.mybatis.entity   # 自己的包名
  mapper-locations: classpath:mappers/*xml
​
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
 

5.pom文件

<?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>
    <groupId>com.xiaoli</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</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.2.2</version>
        </dependency>
​
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </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>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
​
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.xiaoli.DemoApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
​
</project>

6.查询全部操作

controller层

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer userServer;
​
    /**
     * 查询
     * @return
     */
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userServer.findAll();
    }
    }

server层

@Service
public class UserServer {
    @Autowired
    private UserMapper userMapper;
​
    /**
     * 查询全部用户
     * @return
     */
    public List<User> findAll(){
        return userMapper.findAll();
    }
    }

mapper层

@Mapper
public interface UserMapper {
    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    List<User> findAll();
    }

测试:Apifox或者postman

7.修改-新增操作

controller层

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer userServer;
​
    /**
     * 新增-修改
     */
    @PostMapping("/save")
    public Integer save(@RequestBody User user){
        return userServer.save(user);
    }
}

server层

@Service
public class UserServer {
    @Autowired
    private UserMapper userMapper;
​
    /**
     * 新增--修改
     */
    public Integer save(User user) {
        if ((user.getId() == null) ){  //如果id为空,则为新增
            return userMapper.save(user);
        } else {                       //否则为修改
            return userMapper.update(user);
        }
    }
    }

mapper层

@Mapper
public interface UserMapper {
    /**
     * 新增
     */
    @Insert("insert into user(username,password,sex)values (#{username},#{password},#{sex})")
    Integer save(User user);
      /**
     * 修改
     */
   @Update("update user set username=#{username}, password=#{password}, sex=#{sex} where id=#{id}")
    Integer update(User user);
    }

在resources中创建mapper文件夹,新建一个UserMapper.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="com.xiaoli.mapper.UserMapper">
    <update id="update">
        update user
        <set>
            <if test="username !=null">
                user = #{username}
            </if>
            <if test="password !=null">
                password = #{password},
            </if>
            <if test="sex !=null">
                sex = #{sex},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
​
    </update>
</mapper>

测试:

新增测试:

修改测试:

4.删除操作

controller层

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer userServer;
    /**
     * 删除
     */
    @DeleteMapping("{id}")
    public Integer del(@PathVariable Integer id){
        return userServer.delete(id);
    }
}

server层

@Service
public class UserServer {
    @Autowired
    private UserMapper userMapper;
​
    /**
     * 删除
     */
    public Integer delete(Integer id){
        return userMapper.delete(id);
    }
}
​

mapper层

@Mapper
public interface UserMapper {
    /**
     * 删除
     */
    @Delete("delete from user where id=#{id}")
    Integer delete(Integer id);
}

完整代码:

controller层

package com.xiaoli.controller;
​
import com.xiaoli.entity.User;
import com.xiaoli.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
​
import java.util.List;
​
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer userServer;
​
    /**
     * 查询
     * @return
     */
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userServer.findAll();
    }
​
    /**
     * 新增-修改
     */
    @PostMapping("/save")
    public Integer save(@RequestBody User user){
        return userServer.save(user);
    }
​
    /**
     * 删除
     */
    @DeleteMapping("{id}")
    public Integer del(@PathVariable Integer id){
        return userServer.delete(id);
    }
}

server层

package com.xiaoli.server;
​
import com.xiaoli.entity.User;
import com.xiaoli.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
​
import java.util.List;
​
@Service
public class UserServer {
    @Autowired
    private UserMapper userMapper;
​
    /**
     * 查询全部用户
     * @return
     */
    public List<User> findAll(){
        return userMapper.findAll();
    }
​
    /**
     * 新增--修改
     */
    public Integer save(User user) {
        if ((user.getId() == null) ){  //如果id为空,则为新增
            return userMapper.save(user);
        } else {                       //否则为修改
            return userMapper.update(user);
        }
    }
​
    /**
     * 删除
     */
    public Integer delete(Integer id){
        return userMapper.delete(id);
    }
}
​

mapper层:

package com.xiaoli.mapper;
​
import com.xiaoli.entity.User;
import org.apache.ibatis.annotations.*;
​
import java.util.List;
​
@Mapper
public interface UserMapper {
    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    List<User> findAll();
    /**
     * 新增
     */
    @Insert("insert into user(username,password,sex)values (#{username},#{password},#{sex})")
    Integer save(User user);
    /**
     * 修改
     */
    @Update("update user set username=#{username}, password=#{password}, sex=#{sex} where id=#{id}")
    Integer update(User user);
    /**
     * 删除
     */
    @Delete("delete from user where id=#{id}")
    Integer delete(Integer id);
​
}
​

rescourse下的mapper层

<?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.xiaoli.mapper.UserMapper">
    <update id="update">
        update user
        <set>
            <if test="username !=null">
                user = #{username}
            </if>
            <if test="password !=null">
                password = #{password},
            </if>
            <if test="sex !=null">
                sex = #{sex},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
​
    </update>
</mapper>

;