SpringBoot(十一) ----SpringBoot结合mybatis实现增删改查

我们可以使用SpringBoot,将SpringBoot与mybatis结合起来,实现对数据库的增删改查的操作。

接下来举个例子:

第一步,首先创建一个数据库test,并创建表tb_user,向tb_user中插入几条数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
create database test;
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
use test;
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'laowang', '112233');
INSERT INTO `tb_user` VALUES ('2', 'laoli', '123456');

第二步,构建我们的springboot项目,项目结构如下,

 

从项目的结构中,我们可以看到我们需要构建的项目文件,springboot启动类DemoApplication.java、控制层类UserController.java、实体类User.java、DAO层UserMapper.java接口文件、Service层UserService.java、mapping文件夹下UserMapper.xml映射文件、静态资源文件success.html和我们SpringBoot的application.yml配置文件、Maven配置文件pom.xml。

第三步,构建pom.xml文件,文件内容如下:

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.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>1.3.2</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
 
</project>

这里核心引入与mybatis和mysql数据库相关的jar

1
2
3
4
5
6
7
8
9
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
</dependency> 

第四步,配置application.yml数据库文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server:
  port: 8080
 
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
 
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.entity
 
#showSql
logging:
  level:
    com:
      example:
        mapper : debug

第五步,构建controller、service、Dao、Data层文件内容

UserController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.example.controller;
 
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
 
@RestController
@RequestMapping("/testBoot")
public class UserController {
 
    @Autowired
    private UserService userService;
 
    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id){
        return userService.Sel(id).toString();
    }
     
    @RequestMapping("findAll")
    public String findAll(){
        return userService.SelAll().toString();
    }
     
    @RequestMapping("insert/id={id}&username={username}&password={password}")
    public String insert(User user){
        userService.insert(user);
        return "success";
    }
     
    @RequestMapping("delete/id={id}")
    public String delete(User user){
        userService.delete(user);
        return "success";
    }
     
    @RequestMapping("update/id={id}&username={username}&password={password}")
    public String update(User user){
        userService.update(user);
        return "success";
    }
}

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.entity;
 
/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
public class User {
    private Integer id;
    private String username;
    private String password;
    
 
    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;
    }
 
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
     
     
}

UserMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example.mapper;
 
import com.example.entity.User;
 
import java.util.List;
 
import org.springframework.stereotype.Repository;
 
/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
@Repository
public interface UserMapper {
 
    User Sel(int id);
 
    List<User> SelAll();
 
    int insert(User user);
 
    int deleteById(User user);
 
    int updateById(User user);
}

UserMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?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.example.mapper.UserMapper">
 
    <resultMap id="BaseResultMap" type="com.example.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="userName" jdbcType="VARCHAR" property="userName" />
        <result column="passWord" jdbcType="VARCHAR" property="passWord" />
    </resultMap>
 
    <select id="Sel" resultType="com.example.entity.User">
        select * from tb_user where id = #{id}
    </select>
 
    <select id="SelAll" resultType="com.example.entity.User">
        select * from tb_user
    </select>
 
    <insert id="insert" parameterType="com.example.entity.User">
        INSERT INTO tb_user
        (
        id,username,password
        )
        VALUES (
        #{id},
        #{username, jdbcType=VARCHAR},
        #{password, jdbcType=VARCHAR}
        )
    </insert>
 
    <delete id="deleteById">
        Delete from tb_user
        where id=#{id}
    </delete>
    <update id="updateById" parameterType="com.example.entity.User">
        Update tb_user
        SET
        id = #{id},
        username = #{username},
        password = #{password}
        where id = #{id}
    </update>
</mapper>

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.example.service;
 
import com.example.entity.User;
import com.example.mapper.UserMapper;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    public User Sel(int id){
        return userMapper.Sel(id);
    }
    public List<User> SelAll() {
        // TODO Auto-generated method stub
        return userMapper.SelAll();
    }
    public int insert(User user) {
        // TODO Auto-generated method stub
        return userMapper.insert(user);
    }
    public int delete(User user) {
        // TODO Auto-generated method stub
        return userMapper.deleteById(user);
    }
    public int update(User user) {
        // TODO Auto-generated method stub
        return userMapper.updateById(user);
    }
}

构建success.html静态资源文件

success.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
success
</body>
</html>

最后一步,设置启动类

DemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@MapperScan("com.example.mapper") //扫描的mapper
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

然后我们开始启动程序:

测试增加操作:

 

 

测试删除操作:

 

 

 

 

 刚才加的数据删掉了

测试修改操作:

 

 

 

 可以看到id=2的数据已经被修改掉了

测试查询操作:

首先查全部数据

 

根据id查数据

至此我们的增删改查操作完成。

 源码地址:https://github.com/SeulLeo/myspringboot_013

posted @   leagueandlegends  阅读(590)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示