天天看點

spring boot用gradle建構工具整合mybatis

文章目錄

    • 1、Mybatis簡介
    • 2、項目建立
    • 3、entity 實體類代碼
    • 4、dao層代碼
    • 5、service層代碼
    • 6、serviceImpl層代碼
    • 7、mapper層代碼
    • 8、controller層代碼
    • 9、測試
    • 10、補充

1、Mybatis簡介

MyBatis 是一款優秀的持久層架構,它支援定制化 SQL、存儲過程以及進階映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設定參數以及擷取結果集。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生資訊,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java對象)映射成資料庫中的記錄。

2、項目建立

建立一個具有start-web,mybatis,mysql依賴的SpringBoot項目

所有完成後的目錄結構為:

spring boot用gradle建構工具整合mybatis

紅框處為修改和建立

在yaml檔案,也可以是properties檔案裡面配置連接配接資料庫的相關配置

application.yaml:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: 123456
    username: root

logging:
  level:
    com.huhst: debug
           

在資料庫demo下面建立一個student表

(這裡要記住自己的資料庫名,不要無腦複制,XML 檔案内修改為自己本地資料庫名)

CREATE TABLE `student`(
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '唯一辨別id',
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '姓名',
  `age` int(3) NOT NULL COMMENT '年齡',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
           

完成項目初始配置。

3、entity 實體類代碼

package com.example.entity;


/**
 * @author 92306
 */
public class Student {
    private static final long serialVersionUID = -91969758749726312L;
    /**
     * 唯一辨別id
     */
    private Integer id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年齡
     */
    private Integer age;

    /**
     * 擷取id
     *
     * @return
     */
    public Integer getId() {
        return id;
    }

    /**
     * 擷取姓名
     */
    public String getName() {
        return name;
    }

    /**
     * 年齡
     */
    public Integer getAge() {
        return age;
    }

    /**
     * 設定名字
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 設定年齡
     */
    public void setAge(Integer age) {
        this.age = age;
    }

}
           

4、dao層代碼

package com.example.dao;

import com.example.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;


/**
 * @author 92306
 */
@Mapper
@Repository
public interface StudentDao {

    /**
     * 通過ID查詢單條資料
     *
     * @param id 主鍵
     * @return 執行個體對象
     */
    Student queryById(Integer id);

    /**
     * 查詢指定行資料
     *
     * @param offset 查詢起始位置
     * @param limit 查詢條數
     * @return 對象清單
     */
    List<Student> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);


    /**
     * 通過實體作為篩選條件查詢
     *
     * @param student 執行個體對象
     * @return 對象清單
     */
    List<Student> queryAll(Student student);

    /**
     * 新增資料
     *
     * @param student 執行個體對象
     * @return 影響行數
     */
    int insert(Student student);

    /**
     * 修改資料
     *
     * @param student 執行個體對象
     * @return 影響行數
     */
    int update(Student student);

    /**
     * 通過主鍵删除資料
     *
     * @param id 主鍵
     * @return 影響行數
     */
    int deleteById(Integer id);

}
           

代碼說明: dao層屬于資料通路層,與mybatis 的xml檔案互相映射,實作SQL語句的功能。

注解說明: 在dao層的類需要加上 @Mapper的注解,這個注解是mybatis提供的,辨別這個類是一個資料通路層的bean,并交給spring容器管理。并且可以省去之前的xml映射檔案。在編譯的時候,添加了這個類也會相應的生成這個類的實作類。

如果你是用的idea,在serviceImpl中使用 @Autowired注入bean的時候,idea會報錯,但是不影響運作,報錯是因為 @mapper不是spring提供的,當需要自動注入這個bean的時候idea不能 預檢測到這個bean是否可以注入到容器中,不知道新版的idea會不會有這種問題。如果想消除這個報錯,你可以在dao層的類上面加上一個 @Repository,這個注解是spring提供的,這樣就可以預檢測到mapper的bean是可以注冊到spring容器裡面的。

你會發現在代碼中,有的接口的參數是帶了 @Param這個注解的,有的參數是沒有這個注解的。如果你隻有一個參數,這個注解可要可不要。當你有兩個及其以上的注解時,你就需要用這個注解了,不然在對應的xml檔案,它分辨不出來這個參數是哪一個就會報錯,用這個注解的意思就是說辨別這個參數的名稱,以便讓接受參數的一方更好的找到并利用這個值。

5、service層代碼

package com.example.service;

import com.example.entity.Student;
import java.util.List;



/**
 * @author 92306
 */
public interface StudentService {

    /**
     * 通過ID查詢單條資料
     *
     * @param id 主鍵
     * @return 執行個體對象
     */
    Student queryById(Integer id);

    /**
     * 查詢多條資料
     *
     * @param offset 查詢起始位置
     * @param limit 查詢條數
     * @return 對象清單
     */
    List<Student> queryAllByLimit(int offset, int limit);

    /**
     * 新增資料
     *
     * @param student 執行個體對象
     * @return 執行個體對象
     */
    Student insert(Student student);

    /**
     * 修改資料
     *
     * @param student 執行個體對象
     * @return 執行個體對象
     */
    Student update(Student student);

    /**
     * 通過主鍵删除資料
     *
     * @param id 主鍵
     * @return 是否成功
     */
    boolean deleteById(Integer id);

}
           

代碼說明: 這是服務層的接口,serviceImpl對應服務層接口的實作。

6、serviceImpl層代碼

package com.example.service.impl;

import com.example.entity.Student;
import com.example.dao.StudentDao;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    /**
     * 通過ID查詢單條資料
     *
     * @param id 主鍵
     * @return 執行個體對象
     */
    @Override
    public Student queryById(Integer id) {
        return this.studentDao.queryById(id);
    }

    /**
     * 查詢多條資料
     *
     * @param offset 查詢起始位置
     * @param limit 查詢條數
     * @return 對象清單
     */
    @Override
    public List<Student> queryAllByLimit(int offset, int limit) {
        return this.studentDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增資料
     *
     * @param student 執行個體對象
     * @return 執行個體對象
     */
    @Override
    public Student insert(Student student) {
        this.studentDao.insert(student);
        return student;
    }

    /**
     * 修改資料
     *
     * @param student 執行個體對象
     * @return 執行個體對象
     */
    @Override
    public Student update(Student student) {
        this.studentDao.update(student);
        return this.queryById(student.getId());
    }

    /**
     * 通過主鍵删除資料
     *
     * @param id 主鍵
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.studentDao.deleteById(id) > 0;
    }
}
           

代碼說明: @Service辨別這個bean是service層的,也就是服務層,并交給spring容器管理。參數的value屬性是這個bean的名稱,也可以不寫,預設為類名。

關于@Resource與 @Autowired,前面我們在serviceImpl裡面需要用到dao層的方法的時候,不是直接new一個對象,在哪需要就在哪new,而是利用注解,實作自定注入裝配,利用spring容器管理這些bean,這樣寫出來的代碼是松耦合的,類之間的耦合度更低,維護性就相對提高了。

@Resource與 @Autowired是可以起到一個相同的作用。根據包名就可以看到,他們不是一個包裡面的。差別如下:

1. @Autowired預設按類型裝配,預設情況下必須要求依賴對象必須存在,如果要允許null值,可以設定它的required屬性為false,如:@Autowired(required=false) ,這個注解是屬于spring的,如果我們想使用名稱裝配可以結合 @Qualifier 注解進行使用。

2. @Resource預設按照名稱進行裝配,名稱可以通過name屬性進行指定,如果沒有指定name屬性,當注解寫在字段上時,預設取字段名進行安裝名稱查找,如果注解寫在setter方法上預設取屬性名進行裝配。當找不到與名稱比對的bean時才按照類型進行裝配。但是需要注意的是,如果name屬性一旦指定,就隻會按照名稱進行裝配。這個注解屬于J2EE的。

7、mapper層代碼

<?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.dao.StudentDao">
    <resultMap type="com.example.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
    </resultMap>

    <!--查詢單個-->
    <select id="queryById" resultMap="StudentMap">
        select
          id, name, age
        from demo.student
        where id = #{id}
    </select>

    <!--查詢指定行資料-->
    <select id="queryAllByLimit" resultMap="StudentMap">
        select
          id, name, age
        from demo.student
        limit #{offset}, #{limit}
    </select>

    <!--通過實體作為篩選條件查詢-->
    <select id="queryAll" resultMap="StudentMap">
        select
        id, name, age
        from demo.student
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into demo.student(name, age)
        values (#{name}, #{age})
    </insert>

    <!--通過主鍵修改資料-->
    <update id="update">
        update demo.student
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通過主鍵删除-->
    <delete id="deleteById">
        delete from demo.student where id = #{id}
    </delete>

</mapper>
           

這裡面對應了SQL的增删改查語句,然後在dao層的方法,對應了每一個SQL語句,這裡面SQL語句的id,對應dao層的每一個接口方法。

預設的配置是檢測不到這個xml檔案的,然後我們需要做以下的配置。

把xml檔案放在resources檔案夾下面的dao檔案夾下面。

在yaml裡面加上以下配置。

mybatis:
  type-aliases-package: com.example.entity
  mapper-locations: classpath:dao/*Mapper.xml

           

8、controller層代碼

controller層的代碼我們是用來測試的,一般也是傳回資料給前端的地方。

package com.example.controller;

import com.example.entity.Student;
import com.example.service.StudentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * @author 92306
 */
@RestController
@RequestMapping("student")
public class StudentController {
    /**
     * 服務對象
     */
    @Resource
    private StudentService studentService;

    /**
     * 通過主鍵查詢單條資料
     *
     * @param id 主鍵
     * @return 單條資料
     */
    @GetMapping("selectOne")
    public Student selectOne(Integer id) {
        return this.studentService.queryById(id);
    }

}
           

代碼說明: @RestController 這個注解等效于 @Controller加上 @ResponseBody,添加了這個注解就是讓這個類傳回json串,這是spring内部提供的json解析。@RequesMapping 注解是一個位址映射的注解。就是根據這個位址,可以找到這個方法,這個類,注解到類上,就相當于方法的父類位址。

9、測試

我們先在資料庫裡面添加一條資料。

然後在浏覽器輸入:localhost:8080/student/selectOne?id=2 就可以看到我們拿到的資料了。

端口配置根據自己項目而定。在yaml檔案修改

10、補充

在mapper的接口上使用@Mapper注解,在編譯之後會生成相應的接口實作類。

每個mapper接口上都要使用@Mapper注解,這樣太麻煩了,可以在spring boot啟動項裡添加@MapperScan注解。

在DemoApplication裡添加@MapperScan(“com.example.dao”) 注解

package com.example;

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

@SpringBootApplication
@MapperScan("com.example.dao")
public class DemoApplication {

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

}

           

Springboot啟動類上面添加@MapperScan注解,就指定mapper接口所在的包,然後包下面的所有接口在編譯之後都會生成相應的實作類,還可以使用掃描多個mapper,用逗号分隔開@MapperScan(“com.example1.dao”,“com.example2.dao”)

文章目錄

    • 1、Mybatis簡介
    • 2、項目建立
    • 3、entity 實體類代碼
    • 4、dao層代碼
    • 5、service層代碼
    • 6、serviceImpl層代碼
    • 7、mapper層代碼
    • 8、controller層代碼
    • 9、測試
    • 10、補充

參考博文:

https://www.cnblogs.com/swzx-1213/p/12698222.html

https://www.cnblogs.com/Amywangqing/p/12896663.html

繼續閱讀