springboot之结合mybatis增删改查解析

1. 场景描述

本节结合springboot2、springmvc、mybatis、swagger2等,搭建一个完整的增删改查项目,希望通过这个基础项目,能帮忙朋友快速上手springboot2项目。

2. 解决方案

2.1新建springboot项目

使用idea新建springboot项目(springboot项目快速搭建

(1)new project

(2)gav设置

2.2 项目整体图及说明

2.2.1 整体图

2.2.2 说明

项目包含4大内容

(1)pom.xml

maven项目必备,用于定义项目、获取jar包、打包等。

(2)项目配置文件

有两个,一个是项目内配置文件;一个是用于mybatis-generate生成相关数据库操作文件。

(3)spcrudapplication

项目启动类,springboot项目必备。

(4)springmvc对应类。

包含controller、service、db等相关类。

2.3 详细说明

2.3.1 pom文件
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.laowang</groupId>
    <artifactId>spcrud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spcrud</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
     <!--1.web启动包 软件老王-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--2. 数据库 软件老王-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>

        <!--3. swagger 软件老王-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!--4.mybatis 软件老王-->
        <!--mybatis-->
        <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>

    </dependencies>

     <!--5.打包 软件老王-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                  <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

说明:

包含5块内容

(1)web启动包 ;

(2)数据库 ;

(3)swagger;

(4)mybatis;

(5)打包;

2.3.2 资源文件

(1)application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ruanjianlaowang?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

说明: 数据库配置文件,连接、用户名、密码

(2)mybatis资源文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <classPathEntry
            location="E:\m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--<plugin type="org.mybatis.generator.plugins.ExamplePagePlugin"/>-->
        <!--<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>-->
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/ruanjianlaowang"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.laowang.spcrud.db.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="com.laowang.spcrud.db.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.laowang.spcrud.db.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <table tableName="t_laowang" domainObjectName="TLaowang" enableInsert="true"
               enableDeleteByPrimaryKey="true"
               enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true"
               enableCountByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="false"/>
            <generatedKey column="id" sqlStatement="MYSQL" identity="true"/>
        </table>


    </context>
</generatorConfiguration>

说明:

包含几块内容:

(a)classPathEntry 标签定义的是mysql-connector的jar包地址

(b)jdbcConnection 数据库连接信息

(c)javaModelGenerator、sqlMapGenerator、javaClientGenerator定义的是生成文件存放的地址;

(d)table具体执行生成代码的tabel,增加几个标签,不生成example方法。

2.3.3 启动类
package com.laowang.spcrud;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@MapperScan("com.laowang.spcrud.db.mapper")
public class SpcrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpcrudApplication.class, args);
    }

}

说明:

@SpringBootApplication所有springboot项目启动必备

@EnableSwagger2 启动swagger

@MapperScan加载mpper文件。

2.3.4 springmvc类

(1)TestController

package com.laowang.spcrud.controller;

import com.laowang.spcrud.db.entity.TLaowang;
import com.laowang.spcrud.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private TestService testService;

    /**
     *  增加
     * @auther: 软件老王
     */
    @RequestMapping(value ="/save", method = RequestMethod.POST)
    @ResponseBody
    public  String save(TLaowang tLaowang) {
        testService.insertRecord(tLaowang);
        return "保存成功,i'm 软件老王!";
    }
    /**
     *  删除
     * @auther: 软件老王
     */
    @RequestMapping(value ="/delete", method = RequestMethod.POST)
    @ResponseBody
    public  String delete(int id) {
        testService.deleteByPrimaryKey(id);
        return "删除成功,i'm 软件老王!";
    }

    /**
     *  更新
     * @auther: 软件老王
     */
    @RequestMapping(value ="/update", method = RequestMethod.POST)
    @ResponseBody
    public  String update(TLaowang tLaowang) {
        testService.updateByPrimaryKeySelective(tLaowang);
        return "更新成功,i'm 软件老王!";
    }
    /**
     *  查询
     * @auther: 软件老王
     */
    @RequestMapping(value ="/select", method = RequestMethod.POST)
    @ResponseBody
    public  Object select(int id) {
        return testService.selectByPrimaryKey(id);
    }
}

ctroller类包含增删改查4个方法,使用了rest请求的方式。

(2)TestService

package com.laowang.spcrud.service;

import com.laowang.spcrud.db.entity.TLaowang;
import com.laowang.spcrud.db.mapper.TLaowangMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestService {
    @Autowired
    private TLaowangMapper tLaowangMapper;


    /**
     *  增加
     * @auther: 软件老王
     */
    public  void insertRecord(TLaowang tLaowang) {
        tLaowangMapper.insert(tLaowang);
    }

    /**
     *  删除
     * @auther: 软件老王
     */
    public  void deleteByPrimaryKey(int id) {
        tLaowangMapper.deleteByPrimaryKey(id);
    }
    /**
     *  更新
     * @auther: 软件老王
     */
    public  void updateByPrimaryKeySelective(TLaowang tLaowang) {
        tLaowangMapper.updateByPrimaryKeySelective(tLaowang);
    }

    /**
     *  查询
     * @auther: 软件老王
     */
    public  TLaowang selectByPrimaryKey(int id) {
        return tLaowangMapper.selectByPrimaryKey(id);
    }
}

TestService类,增删改查的服务类。

(3)实体类TLaowang

package com.laowang.spcrud.db.entity;

public class TLaowang {
    private Integer id;

    private String name;

    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
}

操作实体类,包含三个字段:id、name、password

(4)mpper接口类TLaowangMapper

package com.laowang.spcrud.db.mapper;

import com.laowang.spcrud.db.entity.TLaowang;

public interface TLaowangMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TLaowang record);

    int insertSelective(TLaowang record);

    TLaowang selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(TLaowang record);

    int updateByPrimaryKey(TLaowang record);
}

(5)mapper接口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.laowang.spcrud.db.mapper.TLaowangMapper">
  <resultMap id="BaseResultMap" type="com.laowang.spcrud.db.entity.TLaowang">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, password
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_laowang
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_laowang
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.laowang.spcrud.db.entity.TLaowang">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into t_laowang (name, password)
    values (#{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.laowang.spcrud.db.entity.TLaowang">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into t_laowang
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        name,
      </if>
      <if test="password != null">
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.laowang.spcrud.db.entity.TLaowang">
    update t_laowang
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.laowang.spcrud.db.entity.TLaowang">
    update t_laowang
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

4与5在一起,这里使用了mybatis自动生成的增删改查方法,未做扩展,真实项目中除了这几个外,肯定还会做些扩展,比如根据name查询等。

2.4 数据库建表语句

CREATE TABLE `t_laowang` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

2.5 swagger效果

http://localhost:8080/swagger-ui.html

spring boot 整合mybatis 的xml版本

两个比较常用的mybatis扩展框架。

  • common mapper https://github.com/abel533/Mapper/wiki
  • mybatisplus https://mp.baomidou.com/guide/quick-start.html

首先是项目的依赖,完整的pom文件如下:

<?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.example</groupId>
    <artifactId>demo-boot-mybatis-xml</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.16</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

application.yml文件配置

server:
  port: 8080

spring:

  datasource:
    name: test
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: root


mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.example.model  # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

测试的数据库脚本

CREATE TABLE t_user(
  user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  user_name VARCHAR(255) NOT NULL ,
  password VARCHAR(255) NOT NULL ,
  phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

配置mybatis-generator自动生成代码的相关配置

${basedir}/src/main/resources/generator/generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="D:\code\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=utf-8" userId="root" password="root"/>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>
XML 复制 全屏

运行maven插件org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate

运行maven插件org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate

"C:\Program Files\Java\jdk1.8.0_191\bin\java.exe" -Dmaven.multiModuleProjectDirectory=D:\ideaworkspace_demo\demo-boot-mybatis-xml -Dmaven.home=D:\software\idea\plugins\maven\lib\maven3 -Dclassworlds.conf=D:\software\idea\plugins\maven\lib\maven3\bin\m2.conf -javaagent:D:\software\idea\lib\idea_rt.jar=6721:D:\software\idea\bin -Dfile.encoding=UTF-8 -classpath D:\software\idea\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar org.codehaus.classworlds.Launcher -Didea.version=2018.3.5 org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building demo-boot-mybatis-xml 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ demo-boot-mybatis-xml ---
[INFO] Connecting to the Database
Tue Apr 09 11:16:14 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[INFO] Introspecting table t_user
log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] Generating Record class for table t_user
[INFO] Generating Mapper Interface for table t_user
[INFO] Generating SQL Map for table t_user
[INFO] Saving file UserMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.180 s
[INFO] Finished at: 2019-04-09T11:16:14+08:00
[INFO] Final Memory: 15M/245M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0

以上步骤就可以使用generator自动生成model和dao层的代码了。

把mybatis的mapper加入到IoC容器中。

package com.example;

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

@SpringBootApplication
//此注解会把该包下的mapper添加到spring的ioc容器中
@MapperScan("com.example.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}
package com.example.mapper;

import com.example.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> selectAll();
}
C# 复制 全屏

以上就是项目的基本搭建过程,idea可能会提示mapper无法注入,因为idea并不知道MapperScan注解已经把那些接口添加到容器中了,实际并不影响正常运行。

项目源码:https://github.com/lingEric/demo-boot-mybatis-xml

 

posted @ 2021-03-11 00:30  hanease  阅读(118)  评论(0编辑  收藏  举报