Spring boot整合Mybatis二:使用註解方式實現與數據庫交互

Spring boot整合Mybatis一中我新建了一個整合了MyBatis的Spring boot工程。現在此工程架構上作編碼操作,使用註解方式實現與數據庫交互。(寫博客期間工作事務耽擱了一下,所以有些類的創建日期不同。)

1、新增幾個包,改application.properties文件爲application.yml(這樣使配置更簡潔,少寫很多前綴),現工程機構如下:

2、 配置pom.xml文件,增加json依賴,增加lombok插件引用,配置啓動路徑。下面是我的pom文件全部:

<?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 http://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.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aigov.springboot-mybatis</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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</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>
        <!-- 增加json依賴 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 增加lombok插件引用-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- 配置啓動入口路徑 -->
                <configuration>
                    <mainClass>com.aigov.springbootmybatis.springbootmybatis.SpringbootMybatisApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、配置application.yml文件:端口,數據庫。下面是我的application.yml文件全部內容:

server:
  port: 8001

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    name: test
    url: jdbc:mysql://localhost:3306/aigov_core?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
    username: root
    password: 123456
  mvc:
    servlet:
      path: /springboot_mybatis

以上項目基礎配置就完成了。

4、用mysql的客戶端Navicat 新建一個student表,表結構:

5、新建實體類 Student.java,這裏用到了lombok的@Data註解,省去了geter seter.下面是我的Student 類的全部:

package com.aigov.springbootmybatis.springbootmybatis.domain;

import lombok.Data;

/**
 * @author : aigoV
 * @date :2019/5/7
 * 對應數據表的學生實體類
 **/
@Data
public class Student {
    private Integer n_id;
    private String c_xm;
    private Integer n_nl;
    private String c_xb;
}

6、編寫dao層的 mapper接口 StudentMapper.java。以下是該文件裏的代碼:

package com.aigov.springbootmybatis.springbootmybatis.mapper;

import com.aigov.springbootmybatis.springbootmybatis.domain.Student;
import org.apache.ibatis.annotations.*;

/**
 * @author : aigoV
 * @date :2019/5/14
 * 定義學生的增刪改查接口
 * 這裏就是用註解的方式實現與數據庫交互
 **/
@Mapper
public interface StudentMapper {
    /**
     * 新增學生信息
     * @param s
     * @return
     */
    @Insert("INSERT INTO aigov_core.student (n_id,c_xm,n_nl,c_xb) VALUES(#{n_id},#{c_xm},#{n_nl},#{c_xb});")
    int addStudent(Student s);

    /**
     * g根據學生id刪除學生信息
     * @param n_id
     * @return
     */
    @Delete("DELETE FROM aigov_core.student WHERE n_id = #{n_id}")
    int deleteStuById(@Param("n_id") Integer n_id);

    /**
     * 根據姓名修改學生信息
     * @param n_nl
     * @param c_xm
     * @return
     */
    @Update("UPDATE aigov_core.student SET n_nl = #{n_nl} WHERE c_xm = #{c_xm}")
    int updateStudent(@Param("n_nl") Integer n_nl,@Param("c_xm") String c_xm);

    /**
     * 根據性別查詢學生信息
     * @param c_xb
     * @return
     */
    @Select("SELECT * FROM aigov_core.student WHERE c_xb = #{c_xb}")
    Student findByXb(@Param("c_xb") String c_xb);
}

7、service業務層--處理相關業務。

在這個案例裏沒有複雜業務要處理,所以你可能會感覺這一層沒有存在意義。實際工作中業務是重中之重,所以我還是按照三層架構思想把這一層寫出來,便於新手瞭解。

package com.aigov.springbootmybatis.springbootmybatis.service;

import com.aigov.springbootmybatis.springbootmybatis.domain.Student;
import com.aigov.springbootmybatis.springbootmybatis.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author : aigoV
 * @date :2019/5/14
 * 處理學生對象信息的業務層
 **/
@Service
public class StudentService {

    @Autowired
    StudentMapper studentMapper;//如果這裏報錯:注入不了。就在mapper類上加一個 @Component

    /** 插入學生信息 **/
    public void addStu(Student s){
        studentMapper.addStudent(s);
    }

    /** 刪除學生信息 **/
    public void deleteStu(int n_id){
        studentMapper.deleteStuById(n_id);
    }

    /**修改學生信息*/
    public void upddateStu(Integer n_nl,String c_xm){
        studentMapper.updateStudent(n_nl,c_xm);
    }

    /** 查詢學生信息**/
    public Student findStu(String c_xb){
        return studentMapper.findByXb(c_xb);
    }

}

8、控制層

主要把處理前端發送過來得到請求,並在這裏將相應請求轉發給相應業務層處理。

我這裏前端使用postman,模擬發送請求。這裏對請求相關不做詳解,簡單瞭解一下,之後會再寫個詳細的基於Springboot框架下的請求及響應的demo。

控制層簡單解釋及代碼如下:

@RestController:相當於@ResponseBody+@Controller

@RequestMapping("/xxx"):處理請求地址的映射,若用於類上,表示類中的所有響應請求的方法都是以該地址作爲父路徑。

package com.aigov.springbootmybatis.springbootmybatis.controller;

import com.aigov.springbootmybatis.springbootmybatis.domain.Student;
import com.aigov.springbootmybatis.springbootmybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : aigoV
 * @date :2019/5/14
 * 學生信息--控制層
 **/
@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

    //增加
    @RequestMapping("/addStu")
    public void addStu(Student s){
         studentService.addStu(s);
    }

    //刪除
    @RequestMapping("/deleteStu")
    public void deleteStu(int n_id){
        studentService.deleteStu(n_id);
    }

    //更新
    @RequestMapping("/updateStu")
    public void updateStu(int n_nl,String c_xm){
        studentService.upddateStu(n_nl,c_xm);
    }

    //查詢
    @RequestMapping("/findStu")
    public Student findStu(String c_xb){
        return studentService.findStu(c_xb);
    }

}

9、啓動入口類

添加事務註解  @EnableTransactionManagement。詳細代碼如下:

package com.aigov.springbootmybatis.springbootmybatis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
public class SpringbootMybatisApplication {

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

}

10、測試:

啓動項目

保證mysql本地服務處於開啓狀態

打開postman 模擬發送請求,開始測試。(沒有postman,百度下載安裝)

測試每一個方法,全部通過,數據庫數據正確發生變更:

至此,基於Springboot+mybatis的sql註解開發方式的案例寫完了,有問題歡迎交流斧正。

注:

1、我在編寫過程中出現的小bug及解決辦法:

https://blog.csdn.net/aigoV/article/details/90202671

https://blog.csdn.net/aigoV/article/details/90201572

2、源代碼(晚點傳上來)

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章