SpringBoot集成MyBatis

7 篇文章 0 订阅
2 篇文章 0 订阅

SpringBoot集成MyBatis

SpringBoot与之前的SSM整合相比真的是不要太轻松,这里是SpringBoot与Mybatis的简单整合,使用了MyBatis反向工程,简单的过程如下

1、创建一个Spring Initializr项目,记得后面添加Spring Web

在这里插入图片描述


2、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.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.study.springboot</groupId>
    <artifactId>012-springboot-mybatis</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--SpringBoot框架web项目起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--MySQL依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--MyBatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <!--手动指定文件夹为resources-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>

            </resource>
        </resources>

        <plugins>
            <!--SpringBoot项目编译打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!--mybatis 代码自动生成插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins
    </build
</project>

这里有几点必要说明

    1)因为我把SpringBoot框架web项目的test的起步依赖删掉了,因此需把test下的java目录下的包结构全部删除
    2)因为的mapper.xml文件不在resources下,所以我使用了resources标签指定文件夹,如果在resources下的mapper目录中,需在springboot配置文件加入mybatis.mapper-locations=classpath:mapper/*.xml
    3) mybatis 代码自动生成插件,这个插件就是进行Mybatis反向工程的插件


3、在模块的根目录下创建GeneratorMapper.xml文件
我的项目结构图

在这里插入图片描述

编写GeneratorMapper.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>
    <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
    <classPathEntry location="F:\Environment\MySql Connector Java 5.1.23\mysql-connector-java-5.1.23-bin.jar"/>
    <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
    <context id="tables" targetRuntime="MyBatis3">
        <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- 配置数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.11.128:3306/springboot"
                        userId="root"
                        password="2580">
        </jdbcConnection>
        <!-- 生成 model 类,targetPackage 指定 model 类的包名, targetProject 指定
       生成的 model 放在 eclipse 的哪个工程下面-->
        <javaModelGenerator targetPackage="org.study.springboot.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的
       包名, targetProject 指定生成的 mapper.xml 放在 eclipse 的哪个工程下面 -->
        <sqlMapGenerator targetPackage="org.study.springboot.mapper"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包
       名, targetProject 指定生成的 Mapper 接口放在 eclipse 的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="org.study.springboot.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 数据库表名及对应的 Java 模型类名 -->
        <table tableName="t_student" domainObjectName="Student"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

    相关作用已经注释,根据自己的情况修改相关配置。(http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd会报错,但没有关系),运行插件,就可以生成model和mapper的所有类了,接口和实体类都差不多,这里把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="org.study.springboot.mapper.StudentMapper">

  <resultMap id="BaseResultMap" type="org.study.springboot.model.Student">
    <!--  id标签只能修饰主键字段-->
    <!--result 除了主键以外的字段-->
    <!--
        column 数据库中的字段的名称
        property 映射对象的属性名称
        jdbcType 列中数据库中字段的类型(可以省略不写)
    -->
    <!--
        resultMap作用:
        1.当数据库中字段名称与实体类对象的属性名不一致时,可以进行替换
        2.当前查询的结果没有对象一个表的时候,可以自定义一个结果集
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>

  <!--sql语句片段,将公共的部分抽取出来-->
  <sql id="Base_Column_List">
    id, name, age
  </sql>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_student
    where id = #{id,jdbcType=INTEGER}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_student
    where id = #{id,jdbcType=INTEGER}
  </delete>

  <insert id="insert" parameterType="org.study.springboot.model.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>

  <!--
      suffixOverrides:去除多余的逗号
  -->
  <insert id="insertSelective" parameterType="org.study.springboot.model.Student">
    insert into t_student
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="org.study.springboot.model.Student">
    update t_student
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <update id="updateByPrimaryKey" parameterType="org.study.springboot.model.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

4、创建service的相关类,在service的实现类的上面加入@Service注解。这里只给出实现类的代码
package org.study.springboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.study.springboot.mapper.StudentMapper;
import org.study.springboot.model.Student;
import org.study.springboot.service.StudentService;


@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper mapper;

    @Override
    public Student queryStudentById(Integer id) {
        Student student = mapper.selectByPrimaryKey(id);
        return student;
    }
}

5、创建controller类,并在类的上面加入@Controller注解
package org.study.springboot.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.study.springboot.model.Student;
import org.study.springboot.service.StudentService;

@Controller
public class StudentController {

    @Autowired
    private StudentService service;

    @RequestMapping("/student")
    @ResponseBody
    public Object getStudent(Integer id){
        Student student = service.queryStudentById(id);

        return student;
    }
}


6、编写springboot配置文件,添加数据库相应的信息
#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.11.128:3306/springboot?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=2580


7、在Application的类上面加入@MapperScan注解,并指定包的限定名称,运行即可
package org.study.springboot;

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

@SpringBootApplication
@MapperScan(basePackages = "org.study.springboot.mapper")//开启扫描Mapper接口的包以及子目录
public class Application {

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

}

注:此处的@MapperScan注解可不写,可在相应的mapper接口上面添加@Mapper注解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值