SpringBoot 整合 Mybatis(入門版)

SpringBoot 整合 Mybatis

基本信息

技術棧

Spring Boot 2.4.五、Mybatisjava

學習目的

SpringBoot 整合 Mybatismysql

項目詳解

新建一個 Spring Initializr 項目

image-20210519172857294.png

建立項目的文件結構以及選擇 jdk 的版本

image-20210519173013426.png

選擇項目所須要的依賴

image.png

修改項目名,點擊 Finish 完成

image.png

建好項目後生成的 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.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.malf</groupId>
    <artifactId>springboot_mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

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

</project>

修改配置文件

本文不使用 application.properties 文件,而使用更加簡潔的 application.yml 文件。將 resource 文件夾下原有的 application.properties 文件刪除,建立 application.yml 配置文件(備註:SpringBoot 底層會把 application.yml 文件解析爲application.properties),本文建立了兩個 yml 文件(application.yml 和 application-dev.yml)git

application.yml
spring:
  profiles:
    active: dev
application-dev.yml
server:
  port: 8000
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.malf.entity
#showSql
logging:
  level:
    com:
      example:
        mapper : debug
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot_mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

數據庫表結構

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

建立實體類實現業務流程

建立包 controller、entity、dao、service,resources 下建立 mapping 文件夾,用於寫 sql 語句,也能夠用註解的方式直接寫在 mapper 文件裏。web

entity
package com.malf.entity;

/**
 * @author 巔峯小詞典
 * @description
 * @date 2021/5/20
 * @project springboot_mybatis
 */
public class User {

    private Integer id;
    private String userName;
    private String passWord;
    private String realName;

    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;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }

}
controller
package com.malf.controller;

import com.malf.service.UserService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 巔峯小詞典
 * @description
 * @date 2021/5/20
 * @project springboot_mybatis
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id) {
        return userService.selectById(id).toString();
    }

}
dao
package com.malf.dao;

import com.malf.entity.User;
import org.springframework.stereotype.Repository;

/**
 * @author 巔峯小詞典
 * @description
 * @date 2021/5/20
 * @project springboot_mybatis
 */
@Repository
public interface UserMapper {

    User selectById(int id);

}
service
package com.malf.service;

import com.malf.entity.User;

/**
 * @author 巔峯小詞典
 * @description
 * @date 2021/5/20
 * @project springboot_mybatis
 */
public interface UserService {

    public User selectById(int id);

}
service.impl
package com.malf.service.impl;

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

import javax.annotation.Resource;

/**
 * @author 巔峯小詞典
 * @description
 * @date 2021/5/20
 * @project springboot_mybatis
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    public User selectById(int id){
        return userMapper.selectById(id);
    }

}
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.malf.dao.UserMapper">
    <resultMap type="com.malf.entity.User" id="User">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="userName" jdbcType="VARCHAR" property="userName"/>
        <result column="passWord" jdbcType="VARCHAR" property="passWord"/>
        <result column="realName" jdbcType="VARCHAR" property="realName"/>
    </resultMap>
    <select id="selectById" resultType="com.malf.entity.User">
        select * from user where id = #{id}
  </select>
</mapper>

最終框架結構

image.png

在啓動類里加上註解用於給出須要掃描的 mapper 文件路徑 @MapperScan("com.malf.dao")

package com.malf;

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

@SpringBootApplication
@MapperScan("com.malf.dao") // 掃描的mapper
public class SpringbootMybatisApplication {

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

}

最後啓動,瀏覽器輸入地址:http://localhost:8000/user/getUser/1

image.png
測試成功,SpringBoot 整合 Mybatis 基本框架就搭建成功了。spring

源碼參考

springboot_mybatissql

相關文章
相關標籤/搜索