SpringBoot integrates Mybatis (annotation + xml)

SpringBoot integrates Mybatis (annotation + xml)


Official documents:

https://mybatis.org/mybatis-3/zh/getting-started.html

It is recommended to use annotations for simple sql, and xml for complex sql

SpringBoot integrates Mybatis (annotation development)

Introduce maven dependency

(When IDEA builds the project, you can choose it directly)

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.4</version>
</dependency>

Configure the application.yml file

server:
  port: 8144
spring:
  #redis
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 3000
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hellomybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

Build entity class, Controller class, Service class

  • Entity class
package com.example.mybatisDemo.entity;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    
    
    private long id;
    private String name;
    private String pwd;
}
  • Controller class
package com.example.mybatisDemo.controller;

import com.example.mybatisDemo.entity.User;
import com.example.mybatisDemo.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("api/user")
public class UserController {
    
    
    private final UserService userService;

    public UserController(UserService userService) {
    
    
        this.userService = userService;
    }

    @GetMapping()
    public List<User> getAllUsers(){
    
    
        return userService.getUsers();
    }

    @DeleteMapping("{id}")
    public int deleteUser(@PathVariable long id){
    
    
        return userService.deleteUser(id);
    }

    @PostMapping
    public int saveUser(@RequestBody User user){
    
    
        return userService.insertUser(user);
    }

    @PutMapping
    public int updateUser(@RequestBody User user){
    
    
        return userService.updateUser(user);
    }

    @GetMapping("{id}")
    public User getUser(@PathVariable long id){
    
    
        return userService.getUser(id);
    }
}
  • Service class

The Service layer is better to define an interface and then implement different implementation classes. If you are lazy, write an implementation class directly.

package com.example.mybatisDemo.service;

import com.example.mybatisDemo.entity.User;
import com.example.mybatisDemo.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.*;


@Service
public class UserService {
    
    
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
    
    
        this.userRepository = userRepository;
    }

    public List<User> getUsers(){
    
    
        return userRepository.getUsers();
    }

    public int deleteUser(long id){
    
    
        return userRepository.deleteUser(id);
    }

    public User getUser(long id){
    
    
        return userRepository.getUser(id);
    }

    public int updateUser(User user){
    
    
        return userRepository.updateUser(user);
    }

    public int insertUser(User user){
    
    
        return userRepository.addUser(user);
    }
}

Build Repository class

package com.example.mybatisDemo.repository;

import com.example.mybatisDemo.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Mapper注解能省去以前复杂的xml配置,直接用注解写sql语句
 * 不添加Repository注解依赖注入会报错(不影响运行),强迫症还是加上吧
 */
@Mapper
@Repository
public interface UserRepository {
    
    
    @Select("select * from user")
    List<User> getUsers();

    @Delete("delete from user where id = #{id}")
    int deleteUser(long id);

    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);

    @Update("update user set name=#{name},pwd=#{pwd} where id = #{id}")
    int updateUser(User user);

    @Select("select * from user where id = #{id}")
    User getUser(long id);
}
  • Then just call it directly

Annotation realizes batch insertion

  • Add the following method to the Repository class
/**
 * 批量插入
 * @param users
 * @return
 * @author Breeze
 * @Description collection对应的是传入的参数名,要跟@Param注解规定的参数名对应上,item是集合中每个成员变量的名字,这里实际是使用了mybatis的动态sql特性
 */
@Insert({
    
    
        "<script>","insert into user(id,name,pwd)",
        "values <foreach collection='users' item='user' index='index' separator=','>",
        "(#{user.id},#{user.name},#{user.pwd})",
        "</foreach>","</script>"
})
int addUsers(@Param("users")List<User> users);
  • Update and insert are the same, the method can be called directly

SpringBoot integrates Mybatis (xml development)

  • The Controller layer and the Service layer remain unchanged, and the entity classes are the same as above

Add the corresponding configuration of mybatis in the configuration file

server:
  port: 8144
spring:
  #redis
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 3000
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hellomybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

## springboot整合mybatis
mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.example.mybatisDemo.entity

  • The configuration here is used to bind the xml file used to write SQL statements, the followingtype-aliases-packageThe binding is the path name of the entity class that needs to be used, so that only the entity class name is written in the xml. Just change it to your own here.

Add UserMapper interface file in the Repository folder

package com.example.mybatisDemo.repository;

import com.example.mybatisDemo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Package: com.example.mybatisDemo.repository
 * @Class: Usermapper
 * @Author: Breeze
 * @Date: 2020/12/1 11:45
 */
@Mapper
@Repository
public interface UserMapper {
    
    
    List<User> queryUserList();

    User selectUserById(int id);

    int addUser(User user);

    int updateUser(User user);

    int deleteUser(int id);
}

Create a new mapper folder dedicated to the ×××Mapper.xml file under the Resources folder, and then create a new UserMapper.xml file

<?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.mybatisDemo.repository.UserMapper">
    <select id="queryUserList" resultType="User">
        select * from user
    </select>

    <select id="selectUserById" resultType="User">
        select * from user where id = #{id}
    </select>

    <insert id="addUser" parameterType="User">
        insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>

    <update id="updateUser" parameterType="User">
        update user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
    <select id="selectUserBy" parameterType="User">
        select * from user where
    </select>
</mapper>
  • The namespace is bound to the mapper class matched by this xml file

Create MyBatis core configuration file (optional)

  • Create a mybatis-config.xml file under the resources folder (the file name can be customized)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--MyBatis核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${spring.datasource.driver-class-name}"/>
                <property name="url" value="${spring.datasource.url}"/>
                <property name="username" value="${spring.datasource.username}"/>
                <property name="password" value="${spring.datasource.password}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  • Generally simpler requirements can be achieved without a core configuration file. The purpose of creating this file is to make more customized configurations to meet more complex requirements. For details, see the official documentation.

The picture shows the current file structure

Insert picture description here

  • At this step, the configuration of xml development and annotation development is completed, and the service layer calls the code of the Dao layer to adjust accordingly.

The difference between annotation development and xml development is limited to the Repository layer (Dao layer), and the Controller layer and Service layer above are common.

Guess you like

Origin blog.csdn.net/qq_42026590/article/details/110114858