狂神說筆記——SpringBoot操作數據庫22-1


SpringBoot操作數據庫(1)

1.整合JDBC

SpringData簡介

  • 對於數據訪問層,無論是 SQL(關系型數據庫) 還是 NOSQL(非關系型數據庫),Spring Boot 底層都是采用 Spring Data 的方式進行統一處理。

  • Spring Boot 底層都是采用 Spring Data 的方式進行統一處理各種數據庫,Spring Data 也是 Spring 中與 Spring Boot、Spring Cloud 等齊名的知名項目。

  • Sping Data 官網:https://spring.io/projects/spring-data

  • 數據庫相關的啟動器 :彈簧啟動參考文檔 (spring.io)

在這里插入圖片描述

整合JDBC

  1. 導入測試數據庫
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT
CHARACTER SET utf8 */;

USE `springboot`;

/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;

CREATE TABLE `department` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部門id',
`department_name` varchar(20) NOT NULL COMMENT '部門名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8;
/*Data for the table `department` */

insert into `department`(`id`,`department_name`) values (101,'技術部'),
(102,'銷售部'),(103,'售后部'),(104,'后勤部'),(105,'運營部');

/*Table structure for table `employee` */
DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇員id',
`last_name` varchar(100) NOT NULL COMMENT '名字',
`email` varchar(100) NOT NULL COMMENT '郵箱',
`gender` int(2) NOT NULL COMMENT '性別1 男, 0 女',
`department` int(3) NOT NULL COMMENT '部門id',
`birth` datetime NOT NULL COMMENT '生日',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
/*Data for the table `employee` */

insert into
`employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) values
(1001,'張三','243357594@qq.com',1,101,'2021-03-06 15:04:33'),(1002,'李
四','243357594@qq.com',1,102,'2021-03-06 15:04:36'),(1003,'王
五','243357594@qq.com',0,103,'2021-03-06 15:04:37'),(1004,'趙
六','243357594@qq.com',1,104,'2021-03-06 15:04:39'),(1005,'孫
七','243357594@qq.com',0,105,'2021-03-06 15:04:45');
  1. 新建一個項目測試:springboot-data-jdbc; 引入相應的模塊!基礎模塊

在這里插入圖片描述

  1. 項目建好之后,發現自動幫我們導入了如下的啟動器:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
  1. 編寫yaml配置文件連接數據庫;
spring: 
  datasource:
    username: root
    password: root
    # ?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
  1. 配置完這一些東西后,就可以直接去使用了!因為SpringBoot已經默認幫我們進行了自動配置;去測試類測試一下:
@SpringBootTest
class Springboot05JdbcApplicationTests {
    // DI注入數據源
    @Autowired
    DataSource dataSource;
    
    @Test
    void contextLoads() throws SQLException {
        // 查看默認數據源
        System.out.println(dataSource.getClass());
        // 獲得連接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        // 關閉連接
        connection.close();
    }

}
  • 結果:可以看到他默認給我們配置的數據源為: class com.zaxxer.hikari.HikariDataSource,我們並沒有手動配置。

在這里插入圖片描述

  • 來全局搜索一下,找到數據源的所有自動配置都在:DataSourceAutoConfiguration文件:
@Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})
protected static class PooledDataSourceConfiguration {
    protected PooledDataSourceConfiguration() {
    }
}
  • 這里導入的類都在 DataSourceConfiguration 配置類下,可以看出 Spring Boot 2.6.3默認使用 HikariDataSource 數據源,而以前版本,如 Spring Boot 1.5默認使用 org.apache.tomcat.jdbc.pool.DataSource 作為數據源;
  • HikariDataSource 號稱 Java WEB 當前速度最快的數據源,相比於傳統的 C3P0 、DBCP、Tomcat jdbc 等連接池更加優秀
  • 可以使用 spring.datasource.type 指定自定義的數據源類型,值為要使用的連接池實現的完全限定名
  • 關於數據源不做過多介紹,有了數據庫連接,顯然就可以CRUD操作數據庫了。但是仍需要先了解一個對象——JdbcTemplate

JdbcTemplate

  1. 有了數據源(com.zaxxer.hikari.HikariDataSource),然后可以拿到數據庫連接 (java.sql.Connection),有了連接,就可以使用原生的 JDBC 語句來操作數據庫;
  2. 即使不使用第三方第數據庫操作框架,如 MyBatis等,Spring 本身也對原生的JDBC 做了輕量級的封裝,即JdbcTemplate
  3. 數據庫操作的所有 CRUD 方法都在 JdbcTemplate 中。
  4. Spring Boot不僅提供了默認的數據源,同時默認已經配置好了 JdbcTemplate 放在了容器中,程序員只需自己注入即可使用。
  5. JdbcTemplate 的自動配置是依賴 org.springframework.boot.autoconfigure.jdbc 包下的JdbcTemplateConfiguration類。

JdbcTemplate主要提供以下幾類方法

  • execute方法:可以用於執行任何SQL語句,一般用於執行DDL語句;
  • update方法及batchUpdate方法:update方法用於執行新增、修改、刪除等語句;batchUpdate 方法用於執行批處理相關語句;
  • query方法及queryForXXX方法:用於執行查詢相關語句;
  • call方法:用於執行存儲過程、函數相關語句。

測試案例

  • 編寫一個Controller,注入jdbcTemplate,編寫測試方法進行訪問測試;
package com.github.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jdbc")
public class JdbcController {
    /** * Spring Boot 默認提供了數據源,默認提供了 org.springframework.jdbc.core.JdbcTemplate * JdbcTemplate 中會自己注入數據源,用於簡化 JDBC操作 * 還能避免一些常見的錯誤,使用起來也不用再自己來關閉數據庫連接 */
    @Autowired
    JdbcTemplate jdbcTemplate;

    /** * 查詢employee表中所有數據 * List 中的1個 Map 對應數據庫的 1行數據 * Map 中的 key 對應數據庫的字段名,value 對應數據庫的字段值 */
    @GetMapping("/list")
    public List<Map<String, Object>> userList(){
        String sql = "select * from employee";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    /** * 新增一個用戶 */
    @GetMapping("/add")
    public String addUser(){
        // 插入語句,注意時間問題
        String sql = "insert into employee(last_name, email,gender,department,birth)" +
                " values ('誇克','243357594@qq.com',1,101,'"+ new Date().toLocaleString() +"')";
        jdbcTemplate.update(sql);
        // 查詢
        return "addOk";
    }

    /** * 修改用戶信息 */
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        // 插入語句
        String sql = "update employee set last_name=?,email=? where id="+id;
        // 數據
        Object[] objects = new Object[2];
        objects[0] = "subei";
        objects[1] = "243357594@163.com";
        jdbcTemplate.update(sql,objects);
        // 查詢
        return "updateOk";
    }

    /** * 刪除用戶 */
    @GetMapping("/delete/{id}")
    public String delUser(@PathVariable("id") int id){
        // 刪除語句
        String sql = "delete from employee where id=?";
        jdbcTemplate.update(sql,id);
        // 查詢
        return "deleteOk";
    }
}

在這里插入圖片描述

至此,CURD的基本操作,使用 JDBC 就搞定了。

2.整合Druid

Druid 簡介

  • Java程序很大一部分要操作數據庫,為了提高性能操作數據庫的時候,又不得不使用數據庫連接池。
  • Druid是阿里巴巴開源平台上一個數據庫連接池實現,結合了 C3P0、DBCP 等DB池的優點,同時加入了日志監控。
  • Druid可以很好的監控 DB 池連接和 SQL 的執行情況,天生就是針對監控而生的DB連接池。
  • Spring Boot 2.0 以上默認使用Hikari數據源,可以說Hikari與Driud都是當前Java Web上最優秀的數據源,我們來重點介紹Spring Boot如何集成Druid數據源,如何實現數據庫監控。
  • Github地址:https://github.com/alibaba/druid

com.alibaba.druid.pool.DruidDataSource 基本配置參數如下:

配置 缺省值 說明
name 配置這個屬性的意義在於,如果存在多個數據源,監控的時候可以通過名字來區分開來。如果沒有配置,將會生成一個名字,格式是:“DataSource-” + System.identityHashCode(this).
url 連接數據庫的url,不同數據庫不一樣。例如: mysql: jdbc:mysql://10.20.153.104:3306/druid2 oracle: jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username 連接數據庫的用戶名
password 連接數據庫的密碼。如果你不希望密碼直接寫在配置文件中,可以使用ConfigFilter。
driverClassName 根據url自動識別 這一項可配可不配,如果不配置druid會根據url自動識別dbType,然后選擇相應的driverClassName
initalSize 0 初始化時建立物理連接的個數。初始化發生在顯示調用init方法,或者第一次getConnection時
maxActive 8 最大連接池數量
maxIdle 8 已經不再使用,配置了也沒效果
minIdle 最小連接池數量
maxWait 獲取連接時最大等待時間,單位毫秒。配置了maxWait之后,缺省啟用公平鎖,並發效率會有所下降,如果需要可以通過配置useUnfairLock屬性為true使用非公平鎖。
poolPreparedStatements false 是否緩存preparedStatement,也就是PSCache。PSCache對支持游標的數據庫性能提升巨大,比如說oracle。在mysql下建議關閉。
maxOpenPreparedStatements -1 要啟用PSCache,必須配置大於0,當大於0時,poolPreparedStatements自動觸發修改為true。在Druid中,不會存在Oracle下PSCache占用內存過多的問題,可以把這個數值配置大一些,比如說100
validationQuery 用來檢測連接是否有效的sql,要求是一個查詢語句。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會其作用。
validationQueryTimeout 單位:秒,檢測連接是否有效的超時時間。底層調用jdbc Statement對象的void setQueryTimeout(int seconds)方法。
testOnBorrow true 申請連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能。
testOnReturn false 歸還連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能
testWhileIdle false 建議配置為true,不影響性能,並且保證安全性。申請連接的時候檢測,如果空閑時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效。
timeBetweenEvictionRunsMillis 1分鍾 (1.0.14) 有兩個含義: 1) Destroy線程會檢測連接的間隔時間,如果連接空閑時間大於等於minEvictableIdleTimeMillis則關閉物理連接 2) testWhileIdle的判斷依據,詳細看testWhileIdle屬性的說明。
numTestsPerEvictionRun 不再使用,一個DruidDataSource只支持一個EvictionRun
numTestsPerEvictionRun 30分鍾 (1.0.14) 連接保持空閑而不被驅逐的最長時間
connectionInitSqls 物理連接初始化的時候執行的sql
exceptionSorter 根據dbType自動識別 當數據庫拋出一些不可恢復的異常時,拋棄連接
filters 屬性類型是字符串,通過別名的方式配置擴展插件,常用 的插件有:監控統計用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
proxyFilters 類型是List,如果同時配置了filters和proxyFilters,是組合關系,並非替換關系

配置數據源

  1. 添加上Druid數據源依賴。
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
  1. 切換數據源;之前已經說過 Spring Boot 2.0 以上默認使用com.zaxxer.hikari.HikariDataSource數據源,但可以通過spring.datasource.type指定數據源。
spring:
  datasource:
    username: root
    password: root
    # ?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 自定義數據源
  1. 數據源切換之后,在測試類中注入DataSource,然后獲取到它,輸出一看便知是否成功切換;

在這里插入圖片描述

  1. 切換成功!既然切換成功,就可以設置數據源連接初始化大小、最大連接數、等待時間、最小連接數 等設置項;可以查看源碼。
spring:
  datasource:
    username: root
    password: root
    # ?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 自定義數據源

    #Spring Boot 默認是不注入這些屬性值的,需要自己綁定
    #druid 數據源專有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防御sql注入
    #如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority
      #則導入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  1. 導入Log4j的依賴
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 為DruidDataSource 綁定全局配置文件中的參數,再添加到容器中,而不再使用Spring Boot的自動生成了;需要自己添加DruidDataSource組件到容器中,並綁定屬性;
package com.github.controller;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    /** * 將自定義的 Druid數據源添加到容器中,不再讓 Spring Boot 自動創建 * 綁定全局配置文件中的 druid 數據源屬性到 com.alibaba.druid.pool.DruidDataSource從而讓它們生效 * @ConfigurationProperties(prefix = "spring.datasource"):作用就是將 全局配置文件中 * 前綴為 spring.datasource的屬性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名參數中 */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}
  1. 去測試類中測試一下;看是否成功!
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
    // DI注入數據源
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        // 查看默認數據源
        System.out.println(dataSource.getClass());
        // 獲得連接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);

        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("druidDataSource 數據源最大連接數:" + druidDataSource.getMaxActive());
        System.out.println("druidDataSource 數據源初始化連接數:" + druidDataSource.getInitialSize());

        // 關閉連接
        connection.close();
    }
}
  • 輸出結果:可見配置參數已經生效!

在這里插入圖片描述

配置 Druid 數據源監控

  • Druid 數據源具有監控的功能,並提供了一個web界面方便用戶查看,類似安裝路由器時,人家也提 供了一個默認的web頁面。
  • 所以第一步需要設置 Druid 的后台管理頁面,比如登錄賬號、密碼等;配置后台管理;
    // 配置 Druid 監控管理后台的Servlet;
    // 內置 Servlet 容器時沒有web.xml文件,所以使用 Spring Boot 的注冊 Servlet 方式
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        // 這些參數可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父類 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); //后台管理界面的登錄賬號
        initParams.put("loginPassword", "123456"); //后台管理界面的登錄密碼

        // 后台允許誰可以訪問
        // initParams.put("allow", "localhost"):表示只有本機可以訪問
        // initParams.put("allow", ""):為空或者為null時,表示允許所有訪問
        initParams.put("allow", "");
        // deny:Druid 后台拒絕誰訪問
        // initParams.put("kuangshen", "192.168.1.20");表示禁止此ip訪問

        // 設置初始化參數
        bean.setInitParameters(initParams);
        return bean;
    }
  • 配置完畢后,訪問: http://localhost:8080/druid/login.html

在這里插入圖片描述

  • 進入之后

在這里插入圖片描述

  • 配置Druid web監控filter過濾器
// 配置 Druid 監控 之 web 監控的 filter
// WebStatFilter:用於配置Web和Druid數據源之間的管理關聯監控統計
@Bean
public FilterRegistrationBean webStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    // exclusions:設置哪些請求進行過濾排除掉,從而不進行統計
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
    bean.setInitParameters(initParams);

    // "/*" 表示過濾所有請求
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

平時在工作中,按需求進行配置即可,主要用作監控!

3.整合MyBatis

整合測試

  1. 導入MyBatis所需要的依賴
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.1</version>
</dependency>
  1. 配置數據庫連接信息
spring:
  datasource:
    username: root
    password: root
    # ?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 自定義數據源

    #Spring Boot 默認是不注入這些屬性值的,需要自己綁定
    #druid 數據源專有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防御sql注入
    #如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority
      #則導入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  1. 測試數據庫是否連接成功!
@SpringBootTest
class Springboot05MybatisApplicationTests {
    // DI注入數據源
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        // 查看默認數據源
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }

}
  1. 創建實體類,導入Lombok
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
    private Integer id;
    private String departmentName;
}
  1. 創建mapper目錄以及對應的Mapper接口——DepartmentMapper.java
// @Mapper: 表示本類是一個 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {

    // 獲取所有部門信息
    List<Department> getDepartments();

    // 通過id獲得部門
    Department getDepartment(Integer id);

}
  1. 對應的Mapper映射文件——DepartmentMapper.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.github.mapper.DepartmentMapper">

    <select id="getDepartments" resultType="Department">
        select * from department;
    </select>

    <select id="getDepartment" resultType="Department" parameterType="int">
        select * from department where id = #{id};
    </select>

</mapper>
  1. maven配置資源過濾問題
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

既然已經提供了MyBatis 的映射配置文件,自然要告訴spring boot這些文件的位置。

# 指定myBatis的核心配置文件與Mapper映射文件
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# 注意:對應實體類的路徑
mybatis.type-aliases-package=com.github.pojo
  1. 編寫部門的DepartmentController進行測試!
@RestController
public class DepartmentController {

    @Autowired
    DepartmentMapper departmentMapper;

    // 查詢全部部門
    @GetMapping("/getDepartments")
    public List<Department> getDepartments(){
        return departmentMapper.getDepartments();
    }

    // 查詢全部部門
    @GetMapping("/getDepartment/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDepartment(id);
    }

}
  • 啟動項目訪問進行測試!

在這里插入圖片描述

增加一個員工類再測試下,為之后做准備。

  1. 新建一個pojo類Employee;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    //1 male, 0 female
    private Integer gender;
    private Integer department;
    private Date birth;

    private Department eDepartment; // 冗余設計

}
  1. 新建一個EmployeeMapper接口
// @Mapper: 表示本類是一個 MyBatis 的 Mapper
@Mapper
@Repository
public interface EmployeeMapper {

    // 獲取所有員工信息
    List<Employee> getEmployees();

    // 新增一個員工
    int save(Employee employee);

    // 通過id獲得員工信息
    Employee get(Integer id);

    // 通過id刪除員工
    int delete(Integer id);

}
  1. 編寫EmployeeMapper.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.github.mapper.EmployeeMapper">

    <resultMap id="EmployeeMap" type="Employee">
        <id property="id" column="eid"/>
        <result property="lastName" column="last_name"/>
        <result property="email" column="email"/>
        <result property="gender" column="gender"/>
        <result property="birth" column="birth"/>
        <association property="eDepartment" javaType="Department">
            <id property="id" column="did"/>
            <result property="departmentName" column="dname"/>
        </association>
    </resultMap>

    <select id="getEmployees" resultMap="EmployeeMap">
        select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname
        from department d,employee e
        where d.id = e.department
    </select>

    <insert id="save" parameterType="Employee">
        insert into employee (last_name,email,gender,department,birth)
        values (#{lastName},#{email},#{gender},#{department},#{birth});
    </insert>

    <select id="get" resultType="Employee">
        select * from employee where id = #{id}
    </select>

    <delete id="delete" parameterType="int">
        delete from employee where id = #{id}
    </delete>

</mapper>
  1. 編寫EmployeeController類進行測試。
@RestController
public class EmployeeController {

    @Autowired
    EmployeeMapper employeeMapper;

    // 獲取所有員工信息
    @GetMapping("/getEmployees")
    public List<Employee> getEmployees(){
        return employeeMapper.getEmployees();
    }

    @GetMapping("/save")
    public int save(){
        Employee employee = new Employee();
        employee.setLastName("kuangshen");
        employee.setEmail("qinjiang@qq.com");
        employee.setGender(1);
        employee.setDepartment(101);
        employee.setBirth(new Date());
        return employeeMapper.save(employee);
    }

    // 通過id獲得員工信息
    @GetMapping("/get/{id}")
    public Employee get(@PathVariable("id") Integer id){
        return employeeMapper.get(id);
    }

    // 通過id刪除員工
    @GetMapping("/delete/{id}")
    public int delete(@PathVariable("id") Integer id){
        return employeeMapper.delete(id);
    }

}

在這里插入圖片描述

測試結果完成!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM