Mybatis SpringBoot integration

Create a SpringBoot project

Here, I choose Spring Initializr in Idea for creation, which can also be created inIO and download it.

Fill in the project name

Check dependencies, Web, JDBC, MyBatis, MySQL

Project created successfully!


Create a user table

Here, for simplicity, I create the user table in a database named Demo:

Insert three pieces of data:

id username age address
1 Zhang SAN 22 hangzhou
2 Li si 19 Beijing
3 Cathy 33 Shanghai

The configuration file

Open the application.properties file and do the following:

# port
server.port=8080
# MySQL configuration
spring.datasource.url=jdbc:mysql:///demo? serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
# MyBatis configuration
mybatis.mapper-locations=classpath:mapper/*.xml
Copy the code

Or you can configure it with yml, and the effect is the same.

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql:///demo? serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.korilweb.demo_mybatis.entity
Copy the code

Write the User class

Create an Entity folder and create class user.java:

package com.korilweb.demo_mybatis.entity;

public class User {

    public Integer id;
    public String username;
    public Integer age;
    public String address;


    public Integer getId(a) {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge(a) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress(a) {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", age=" + age +
                ", address='" + address + '\' ' +
                '} '; }}Copy the code

Write Mapper XML files

Under the Resources folder, create a new folder named mapper that will hold all the XML files

In the mapper folder, create a new file named user-mapper. XML:


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.korilweb.demo_mybatis.dao.UserMapper">

    <select id="selectUserById" resultType="com.korilweb.demo_mybatis.entity.User">
        select id, username, age, address
        from user
        where id = #{id}
    </select>
</mapper>
Copy the code

Here, the resultType can be shortened to User, but you need to configure one more entry in application.properties:

mybatis.type-aliases-package=com.korilweb.demo_springcloud.entity
Copy the code

Write the dao layer

Create a new DAO folder and create the interface usermapper.java:

package com.korilweb.demo_mybatis.dao;

import com.korilweb.demo_mybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {

    User selectUserById(int id);
}
Copy the code

We annotate the UserMapper with @mapper, but if we add @mapper to each written Mapper, we can instead annotate the startup class with @mapperscan and specify the package path of the Mapper to be scanned in parentheses:

package com.korilweb.demo_mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.korilweb.demo_mybatis.dao") // With this annotation, we don't need to write @mapper for every Mapper
public class DemoMybatisApplication {

    public static void main(String[] args) { SpringApplication.run(DemoMybatisApplication.class, args); }}Copy the code

Write the service layer

Create a new service folder and create the class userService.java:

package com.korilweb.demo_mybatis.service;

import com.korilweb.demo_mybatis.dao.UserMapper;
import com.korilweb.demo_mybatis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User findUserById(int id) {
        returnuserMapper.selectUserById(id); }}Copy the code

Write the test

@Autowired
private UserService userService;

@Test
void findUserByIdTest(a) {
    User userById = userService.findUserById(1);
    System.out.println(userById);
}
Copy the code

Test results:

User{id=1, username=' zhang3 ', age=22, address=' zhang3 '}Copy the code

Some other simple function implementation (add, delete, change and check)

Find all Users

Add a method to UserMapper first:

List<User> selectAllUsers(a);
Copy the code

Then, write the corresponding SQL statement in user-mapper. XML:

<select id="selectAllUsers" resultType="com.korilweb.demo_mybatis.entity.User">
    select id, username, age, address
    from user
</select>
Copy the code

Finally, call the UserMapper method inside the UserService:

public List<User> findAllUsers(a) {
    return userMapper.selectAllUsers();
}
Copy the code

Testing:

@Test
void findAllUsersTest(a) {
    List<User> users = userService.findAllUsers();
    for(User user : users) { System.out.println(user); }}Copy the code

Test results:

User{id=1, username=' zhang ', age=22, address=' wang '} User{id=2, username=' li ', age=19, address=' Beijing '} User{id=1, username=' zhang ', age=22, address=' wang '} Username =' wang5 ', age=33, address=' wang5 '}Copy the code

Add a user

UserMapper. Java:

int insertUser(User user);
Copy the code

user-mapper.xml

<insert id="insertUser" parameterType="com.korilweb.demo_mybatis.entity.User">
    insert into user (username, age, address)
    values (#{username}, #{age}, #{address})
</insert>
Copy the code

UserService.java

public int addUser(User user) {
    return userMapper.insertUser(user);
}
Copy the code

Testing:

@Test
void addUserTest(a) {
    User user = new User();
    user.setUsername("Daisy");
    user.setAge(18);
    user.setAddress("Guangzhou");
    int result = userService.addUser(user);
    System.out.println(result);
}
Copy the code

Test results:

Returns 1, and you can see that the new user has been added to the database

Update a user’s information

UserMapper. Java:

int updateUserInfo(User user);
Copy the code

User – mapper. XML:

<update id="updateUserInfo" parameterType="com.korilweb.demo_mybatis.entity.User">
    update user
    set username = #{username}, age = #{age}, address = #{address}
    where id = #{id}
</update>
Copy the code

UserService. Java:

public int changeUserInfo(User user) {
    return userMapper.updateUserInfo(user);
}
Copy the code

Testing:

@Test
void changeUserInfoTest(a) {
    User user = new User();
    user.setId(1);
    user.setUsername("Zhang Sanfeng");
    user.setAge(88);
    user.setAddress("Fujian");
    int result = userService.changeUserInfo(user);
    System.out.println(result);
}
Copy the code

Test results:

Returns 1, and you can see in the database that the user information with ID =1 has changed

Deleting a User

UserMapper. Java:

int deleteUserById(int id);
Copy the code

User – mapper. XML:

<delete id="deleteUserById">
    delete from user
    where id = #{id}
</delete>
Copy the code

UserService. Java:

public int deleteUserById(int id) {
    return userMapper.deleteUserById(id);
}
Copy the code

Testing:

@Test
void deleteUserByIdTest(a) {
    int result = userService.deleteUserById(1);
    System.out.println(result);
}
Copy the code

Test results:

Return 1, and you can see that the data with id=1 is deleted


code

Code has been uploaded to Gitee:

Gitee.com/ding_jing_h…