SpringBoot.04.SpringBoot整合MyBatis

x33g5p2x  于2022-04-11 转载在 Spring  
字(7.0k)|赞(0)|评价(0)|浏览(553)

准备工作

1.mapper模板

SpringBoot集成MyBatis我们需要新建mapper文件,这里我们先新建一个mapper模板。打开IDEA,依次选择File->settings->Editor->File and Code Templates,然后选中Files;在name中键入Mapper、在Extension中键入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.christy.mapper">

</mapper>

最后点击Apply->OK;如下图所示:

2.t_user

我们使用数据库christy中的t_user表作为本次使用的数据表,建表语句如下:

USE `christy`;

/*Table structure for table `t_user` */

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) CHARACTER SET utf8 DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `salary` double(7,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

整合MyBatis

1.新建Module

我们选择Spring Initializr的方式新建一个Module,按照下图填写信息后点击Next

Dependencies中选择Spring Web,点击Finish,如下图所示:

2.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.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.christy</groupId>
    <artifactId>springboot-04-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-04-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- spring-boot-starter-test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

        <!-- mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!-- mybatis-spring-boot-starter
          由于springboot整合mybatis版本中默认依赖mybatis 因此不需要额外引入mybati版本,否则会出现冲突
         -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.application.yml

server:
  port: 8804

# datasource
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/christy?characterEncoding=UTF-8
    username: root
    password: 123456

# mybatis
mybatis:
  mapper-locations: classpath:com/christy/mapper/*.xml  #指定mapper配置文件位置
  type-aliases-package: com.christy.entity              #指定起别名所在包

4.Springboot04MybatisApplication.java

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

/**
 * 
 * @author Christy
 * @date 2021/9/2 14:44
 * 
 * @MapperScan 作用在类上,扫描指定包下面的mapper接口
 *             MapperScan可以根据指定的包名一次性扫描所有的接口
 *             Mapper只能作用在指定的某个Mapper接口上
 */
@SpringBootApplication
@MapperScan("com.christy.mapper")
public class Springboot04MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot04MybatisApplication.class, args);
    }
}

5.User.java

/**
 * @Author Christy
 * @Date 2021/9/2 14:48
 **/
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private double salary;

    public User() {
    }

    public User(Integer id, String name, Integer age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

6.UserMapper.java

import com.christy.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @Author Christy
 * @Date 2021/9/2 14:50
 * 我们已经在入口类上加了注解@MapperScan,这里就不要加注解@Mapper了
 **/
// @Mapper
public interface UserMapper {
    /**
     * 查找所有用户
     * @author Christy
     * @date 2021/9/2 14:52
     * @param
     * @return java.util.List<User>
     */
    List<User> findAll();
}

7.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.christy.mapper.UserMapper">
    <select id="findAll" resultType="com.christy.entity.User">
        select * from t_user
    </select>
</mapper>

8.UserService

import com.christy.entity.User;

import java.util.List;

/**
 * @Author Christy
 * @Date 2021/9/2 14:55
 **/
public interface UserService {
    /**
     * 查询所有用户
     * @author Christy
     * @date 2021/9/2 14:56
     * @param 
     * @return java.util.List<com.christy.entity.User>
     */
    List<User> findAll();
}

import com.christy.entity.User;
import com.christy.mapper.UserMapper;
import com.christy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Christy
 * @Date 2021/9/2 14:56
 **/
@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;
    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}

9.UserController.java

import com.christy.entity.User;
import com.christy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Christy
 * @Date 2021/9/2 14:58
 **/
@RestController
@RequestMapping("user")
public class UserController {

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

    @RequestMapping("findAll")
    public List<User> findAll(){
        return userService.findAll();
    }
}

10.测试

我们启动项目,浏览器访问http://localhost:8804/user/findAll,结果如下:

相关文章