【WEEK12】 【DAY3】Integrating MyBatis Framework【English Version】

2024.5.15 Wednesday

13. Integrating MyBatis Framework

Official Documentation: http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Maven Repository Address:
Repository
https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.2.2
I choose version 2.2.2 here (must match with the Spring Boot version).
Version

13.1. Integration Testing

13.1.1. Creating the springboot-05-mybatis Project

Create Project
Create Project
Add Maven support (in Project Structure->Modules, click the plus sign to add the corresponding project), update the Maven, JDK, and Java versions in settings as usual, and update the JDK and Java versions in Project Structure. Modify the Spring Framework version in pom.xml to 2.7.13 and reload Maven.
Remove redundant files.
See details: https://download.csdn.net/download/2401_83329143/89303117
Details

13.1.2. Importing Dependencies Required by MyBatis

Modify 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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-05-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-05-mybatis</name>
    <description>springboot-05-mybatis</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <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>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </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>

13.1.3. Configuring Database Connection Information

13.1.3.1. Modifying application.properties
spring.application.name=springboot-05-mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
13.1.3.2. Modifying Springboot05MybatisApplicationTests.java and Testing
package com.P33;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class Springboot05MybatisApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }

}

Test

13.1.4. Creating the pojo Folder

13.1.4.1. Creating User.java

Create User

package com.P33.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}
13.1.4.2. Modifying pom.xml

Adding lombok support in dependencies

<!--lombok-->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.16.20</version>
</dependency>

13.1.5. Creating the mapper Folder

13.1.5.1. Creating UserMapper.java

Create Mapper

package com.P33.mapper;

import com.P33.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper // This annotation indicates that this is a MyBatis mapper class, or add @MapperScan("com.P33.mapper") in Springboot05MybatisApplication
@Repository // Repository
public interface UserMapper {
    List<User> queryUserList();
    User queryUserById(int id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
}

13.1.6. Creating UserMapper.xml

Create 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=bind a corresponding Dao/Mapper interface-->
<mapper namespace="com.P33.mapper.UserMapper">
<!--  The database used here is custom  -->
    <!--write <cache></cache> to enable caching-->
    <select id="queryUserList" resultType="User">
        SELECT * FROM p37jdbc.users;
    </select>

    <select id="queryUserById" resultType="User">
        SELECT * FROM p37jdbc.users WHERE id = #{id};
    </select>

    <insert id="addUser" parameterType="User">
        INSERT INTO p37jdbc.users (id, NAME, PASSWORD) VALUES (#{id},#{name},#{pwd});
    </insert>

    <update id="updateUser" parameterType="User">
        UPDATE p37jdbc.users SET NAME=#{name},PASSWORD = #{pwd} WHERE id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM p37jdbc.users WHERE id = #{id}
    </delete>

</mapper>

13.1.7. Modifying application.properties

The configuration file must be correct! It’s easy to get a 500 error due to small errors. Also, the ‘#’ sign for comments only takes effect in a new line, it cannot be placed after the configuration line (it turns gray only when it works).

spring.application.name=springboot-05-mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Integrate MyBatis  aliases: Alias
mybatis.type-aliases-package=com.P33.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# classpath indicates the total directory, followed by a : indicating its subdirectory, and if it is /, it is the same level folder

13.1.8. Creating the controller Folder

Creating UserController.java

package com.P33.controller;

import com.P33.mapper.UserMapper;
import com.P33.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    // Query
    @GetMapping("/queryUserList")
    public List<User> queryUserList(){
        List<User> userList = userMapper.queryUserList();
        for (User user : userList){
            System.out.println(user);
        }
        return userList;
    }

    // Add a user
    @GetMapping("/addUser")
    public String addUser() {
        userMapper.addUser(new User(7,"ZzzZzz","123456"));
        return "finish";
    }

    // Update a user
    @GetMapping("/updateUser")
    public String updateUser() {
        userMapper.updateUser(new User(7,"ZzzZzz","999999"));
        return "finish";
    }

    // Delete a user
    @GetMapping("/deleteUser")
    public String deleteUser() {
        userMapper.deleteUser(7);
        return "finish";
    }
}

13.1.9. Restart and Run

Restart and Run
http://localhost:8080/queryUserList

Query User List
User List
http://localhost:8080/addUser

Add User
Add User Result
http://localhost:8080/updateUser
Update User
Update User Result
http://localhost:8080/deleteUser
Delete User
Delete User Result
Delete User Success

13.2. Homework

13.2.1. Import and Improve the springboot-03-web Part into the Real Database

  • 33
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值