Spring Boot 實戰(8) springboot 整合 Mybatis

寫在前面: 我是「揚帆向海」,這個暱稱來源於我的名字以及女朋友的名字。我熱愛技術、熱愛開源、熱愛編程。技術是開源的、知識是共享的。

這博客是對自己學習的一點點總結及記錄,如果您對 Java算法 感興趣,可以關注我的動態,我們一起學習。

用知識改變命運,讓我們的家人過上更好的生活

相關文章:

Springboot 系列文章


一、搭建開發環境

工程的目錄結構如下圖所示:

在這裏插入圖片描述

1. 創建數據庫表

注:我在做的時候是用配置文件的形式自動創建的

department 表

CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

employee 表

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

2. 導入需要的依賴

pom.xml

	<!-- Spingboot相關jar包版本 -->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
	<dependencies>
        <!-- springboot與JDBC整合包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <!-- 標識web應用 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--springboot與mybatis的整合包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- mysql 驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 引入druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

3. 編寫數據源的相關配置

application.yml

spring:
  datasource:
    # 數據源基本配置
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_mybatis?serverTimezone=GMT%2B8
    type: com.alibaba.druid.pool.DruidDataSource
    # 數據源其他配置
    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,去掉後監控界面sql無法統計,'wall'用於防火牆
    filters: stat,wall,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


#    initialization-mode: always
#    schema:
#      - classpath:sql/department.sql
#      - classpath:sql/employee.sql

編寫一個配置類,將數據源引入過來

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    // 配置Druid的監控
    // 配置一個管理後臺的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默認就是允許所有訪問

        bean.setInitParameters(initParams);
        return bean;
    }


    // 配置一個web監控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

二、利用註解的形式整合

1. 編寫實體類

Employee

public class Employee {

    private Integer id;      // 員工id
    private String lastName; // 員工姓名
    private Integer gender;  // 員工性別
    private String email;    // 員工郵箱
    private Integer dId; 	 // 部門id

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }
}

Department

public class Department {

    private Integer id;				// 部門id
    private String departmentName;  // 部門名稱

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}

2. 編寫 Mapper接口層

DepartmentMapper

@Mapper // 指定這是一個操作數據庫的mapper,將接口掃描到容器中
public interface DepartmentMapper {

    /**
     * 查詢
     *
     * @param id
     * @return
     */
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    /**
     * 刪除
     *
     * @param id
     * @return
     */
    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    /**
     * 新增
     *
     * @param department
     * @return
     */
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("Insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    /**
     * 更新
     *
     * @param department
     * @return
     */
    @Update("update department set department_name=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

3. 編寫 Controller 層

DeptController

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * 根據id進行查詢
     *
     * @param id
     * @return
     */
    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    /**
     * 新增部門信息
     *
     * @param department
     * @return
     */
    @GetMapping("/dept")
    public Department insertDept(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
}

在不寫配置文件的情況 自定義mybatis的配置規則,開啓駝峯命名法

@org.springframework.context.annotation.Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

4. 測試

插入一條數據

在這裏插入圖片描述
查詢剛纔插入的數據

在這裏插入圖片描述

去數據庫表表裏面查詢,數據插入進去了
在這裏插入圖片描述

二、利用配置文件的形式整合

1. 編寫 Mapper 接口層

EmployeeMapper

@Mapper
public interface EmployeeMapper {

    /**
     * 根據id查詢員工信息
     *
     * @param id
     * @return
     */
    public Employee getEmpById(Integer id);

    /**
     * 新增員工信息
     *
     * @param employee
     */
    public void insertEmp(Employee employee);
}

2. 編寫全局配置文件

mybatis-config.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="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

3. 編寫 Sql 映射文件

<?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.zxy.springboot.mapper.EmployeeMapper">

    <!-- 根據id查詢員工信息 -->
    <select id="getEmpById" resultType="com.zxy.springboot.pojo.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <!-- 新增員工信息 -->
    <insert id="insertEmp">
        INSERT INTO  employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

4. 在 application.yml 中進行相關配置

mybatis:
  # 全局配置文件的位置
  config-location: classpath:mybatis/mybatis-config.xml
  # mapper 映射文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml

5. 編寫 Controller 層

Controller

@RestController
public class EmpController {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 根據id查詢員工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
    }

    /**
     * 新增員工信息
     *
     * @param employee
     * @return
     */
    @GetMapping("/emp")
    public Employee insertEmp(Employee employee) {
        employeeMapper.insertEmp(employee);
        return employee;
    }
}

6. 測試

在這裏插入圖片描述


由於水平有限,本博客難免有不足,懇請各位大佬不吝賜教!

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