1. 程式人生 > 實用技巧 >java之springboot的mybatis的使用(一)

java之springboot的mybatis的使用(一)

一,我們新建一個空專案

二,我們手動新建專案介面如下:

三,準備動作完成,我們新增pom.xml檔案的依賴

pom.xml

<?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> <groupId>com.nl.testmybatis</groupId> <artifactId>testmybatis</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2
.7.RELEASE</version> </parent> <dependencies> <!--springframework.boot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--這個mysql驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0
.20</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> </dependencies> </project>
四,我們看看各個檔案的程式碼

TestController.java
package com.nl.testmybatis.controllers;


import com.nl.testmybatis.entity.Test;
import com.nl.testmybatis.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private TestMapper testMapper;

    @GetMapping("getTest")
    public List<Test> getTest() {
        return testMapper.getAll();
    }
}
Test.java
package com.nl.testmybatis.entity;

public class Test {
    private Integer id;
    private Integer userId;
    private String content;

    public Integer getId() {
        return id;
    }

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

    public Integer getuserId() {
        return userId;
    }

    public void setuserId(Integer userId) {
        this.userId = userId;
    }

    public String getcontent() {
        return content;
    }

    public void setcontent(String content) {
        this.content = content;
    }
}
TestMapper.java
package com.nl.testmybatis.mapper;

import com.nl.testmybatis.entity.Test;
import org.springframework.stereotype.Repository;

import java.util.List;

/*
 * 這裡加的@Mapper是 MyBatis的備註,
 * 目的是為了讓spring能夠根據xml和這個介面動態生成這個介面的實現。
 * 如果是加@Repository,就是spring生成一個bean,
 * 自動注入service的相關引用中。
 * PS:系統會自動根據方法名在對映檔案中找對應的sql
 * 對映檔案是我們在resources新增的mapper.xml檔案,原理是根據方法名和包名查詢
 * */
@Repository
public interface TestMapper {
    Test getById(int Id);

    //@Insert("INSERT INTO zbChatMsg(userId,content) VALUES(#{userId}, #{content})")
    void insert(Test msg);

    List<Test> getAll();
    void update(Test msg);

    void delete(int id);
}
TestApplication.java
package com.nl.testmybatis;

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

@SpringBootApplication
/*這個必須新增,是掃描注入包的路徑*/
@MapperScan("com.nl.testmybatis.mapper")
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
        System.out.print("ttt");
    }
}

TestMapper.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.nl.testmybatis.mapper.TestMapper">
    <!--BaseResultMap預設公共返回型別-->
    <resultMap id="BaseResultMap" type="com.nl.testmybatis.entity.Test">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="userId" jdbcType="INTEGER" property="userId"/>
        <result column="content" jdbcType="VARCHAR" property="content"/>
    </resultMap>

    <sql id="Base_Column_List">
        id, userId, content
    </sql>
    <select id="getById" parameterType="INTEGER" resultType="com.nl.testmybatis.entity.Test" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from test where id = #{id}
    </select>

    <select id="getAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM test
    </select>
    <insert id="insert" parameterType="com.nl.testmybatis.entity.Test" >
       INSERT INTO
            test
            ( userId, content)
        VALUES
            ( #{userId}, #{content})
    </insert>

    <update id="update" parameterType="com.nl.testmybatis.entity.Test" >
        UPDATE
        test
        SET
        <if test="content != null">content = #{content},</if>
        <if test="userId >0">userId = #{userId}</if>
        WHERE
        id = #{id}
    </update>
    <delete id="delete" parameterType="java.lang.Integer" >
       DELETE FROM
             test
       WHERE
             id =#{id}
    </delete>
</mapper>

application.yml

server:
  port: 8080
#springboot會自動載入spring.datasource.*相關配置,
#資料來源就會自動注入到sqlSessionFactory中,
#sqlSessionFactory會自動注入到Mapper中,
#對了你一切都不用管了,直接拿起來使用就行了。
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://120.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  #是告訴系統在哪裡去找mapper.xml檔案。
  mapper-locations: classpath:mapping/*Mapper.xml
  #設定基本包(包別名)也就是為什麼在mapper.xml中可以只寫一個型別名的原因
  type-aliases-package: com.nl.testmybatis.entity

#showSql
logging:
  level:
    com:
      example:
        mapper : debug

五,除錯結果