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

五,調試結果

六,總結
1》TestApplication的MapperScan不能忘記,我們要掃描改包下的文件,注入容器

 

 

 2》TestMapper.xml我們要注意這個文件里面的包名和命名空間是否給你的一致

 不知道的話這樣找

 

 3》TestMapper.xml的id和類型必須和TestMapper.java接口的一致

 

 

 

 

 



 


免責聲明!

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



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