首頁 > 軟體

SpringBoot MyBatis簡單快速入門例子

2021-07-22 13:00:33

一、MyBatis簡介

MyBatis 是一款優秀的持久層框架,它支援自定義 SQL、儲存過程以及高階對映。MyBatis 免除了幾乎所有的 JDBC 程式碼以及設定引數和獲取結果集的工作。MyBatis 可以通過簡單的 XML 或註解來設定和對映原始型別、介面和 Java POJO(Plain Old Java Objects,普通老式 Java 物件)為資料庫中的記錄。

二、MyBatis使用步驟

 1、MyBatis工程總體目錄結構

2、建立簡單的SpringBoot工程



3、新增MyBatis依賴

  <!--MyBatis-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

4、在資料庫建立USER表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL  DEFAULT '' COMMENT '使用者名稱',
  `password` varchar(50) NOT NULL DEFAULT '' COMMENT '密碼',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;

5、在application.properties設定資料庫連線資訊

#資料庫相關設定
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useAffectedRows=true
spring.datasource.username=root
spring.datasource.password=QQ796413

#mybaits設定
#mapper載入路徑
mybatis.mapper-locations= classpath:mapper/*.xml
#實體包位置
mybatis.type-aliases-package= com.example.mybatisdemo.entity
#myatbis組態檔
mybatis.config-location= classpath:mybatis-config.xml

6、建立USER表對應的實體類

package com.example.mybatisdemo.entity;

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + ''' +
                ", password='" + password + ''' +
                '}';
    }

7、在mapper/UserMapper建立UserMapper.java

package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper{

     User findUserById(Integer id);
}

8、在service/UserService新建UserService.java

package com.example.mybatisdemo.service;

import com.example.mybatisdemo.entity.User;

public interface UserService {
    User findUserById(Integer id);
}

9、在service/impl/UserServiceImpl 建立UserServiceImpl.java

package com.example.mybatisdemo.service.impl;

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

@Service
public class UserServiceImpl implements UserService {
        @Autowired
        private UserMapper userMapper;

        @Override
        public User findUserById(Integer id) {
            return userMapper.findUserById(id);
        }
}

10、在resources下新建mybatis-conf.xml

<?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">

<configuration>
    <settings>
        <!--開啟紀錄檔-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--開啟駝峰命名法-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--開啟全域性延遲載入-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 集合為空時強制返回空集合範例而不是null -->
        <setting name="returnInstanceForEmptyRow" value="true"/>
        <!-- 結果集中value為空時保留key -->
        <setting name="callSettersOnNulls" value="true"/>
    </settings>
</configuration>

11、在resources下mapper檔案下建立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">
<!--注意:1.這裡的namespace要是你usermapper的位置-->
<mapper namespace="com.example.mybatisdemo.mapper.UserMapper">
    <!--注意這裡的返回型別-->
    <resultMap id="BaseResultMap" type="com.example.mybatisdemo.entity.User">
        <result column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
    </resultMap>

    <!--2.id和你的方法名一樣,resultMap為上面的id名一致-->
    <select id="findUserById" resultMap="BaseResultMap">
        select
             id,
             username,
             password
        from
             user
        where
             id= #{id,jdbcType=INTEGER}
    </select>
</mapper>

12、建立UserController.java

package com.example.mybatisdemo.controller;

import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/findUserById")
    public User findUserById(@RequestParam Integer id){
       return userService.findUserById(1);
    }
}

13、測試

工程可以去我的資源下載

到此這篇關於SpringBoot MyBatis快速入門-簡單例子的文章就介紹到這了,更多相關SpringBoot MyBatis入門內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com