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接口的一致

 



原文地址:https://www.cnblogs.com/May-day/p/14172255.html