SpringBoot——SpringBoot集成MyBatis

目录

1 SpringBoot集成MyBatis

1.1 准备工作

1.2 pom.xml文件

1.3 核心配置文件(application.properties)

1.4 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)

1.5 service、controller、启动类

2 DAO 其它开发方式

2.1 Dao接口上添加添加@Mapper

2.2 在启动类上添加@MapperScan


1 SpringBoot集成MyBatis

1.1 准备工作

首先,先准备一张表

 我的表是t_student表,id自动递增

1.2 pom.xml文件

<dependencies>
<!--        springBoot框架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>

<!--        MySql驱动    继承父工程的sql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
<!--            <version>5.1.2</version>   表示修改mysql的版本号,不使用父工程的sql版本号-->
        </dependency>

<!--        mybatis整合springboot框架的起步依赖-->
        <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>
            <!--mybatis 代码自动生成插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>


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

1.3 核心配置文件(application.properties)

server.port=8080
server.servlet.context-path=/

#设置连接数据库得配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

1.4 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)

在这里,我们可以通过逆向工程来直接生成 对应的实体类、dao、mapper。当然生成的dao也只是满足基本的增删改查,需要更多的功能需自己去添加。

<?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="E:\mysql-connector-java-5.1.9.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://localhost:3306/test"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- 生成 entity 类,targetPackage 指定 entity 类的包名, targetProject指定生成的 entity 放在 IDEA 的哪个工程下面-->
        <javaModelGenerator targetPackage="com.liuhaiyang.springboot.entity"
                            targetProject="src\main\java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>
        <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的包名, targetProject 指定生成的 mapper.xml 放在 IDEA 的哪个工程下面 -->
        <sqlMapGenerator targetPackage="com.liuhaiyang.springboot.dao"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包名, targetProject 指定生成的 Mapper 接口放在 IDEA 的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.liuhaiyang.springboot.dao"
                             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>

看一下逆向生成的代码,下面的代码都是通过逆向生成出来的相关注释是我写的,用于理解

实体类

package com.liuhaiyang.springboot.entity;

public class Student {
    private Integer id;

    private String name;

    private Integer age;

    //下面是set()和get()方法,就不看了
}

 dao接口

package com.liuhaiyang.springboot.dao;

import com.liuhaiyang.springboot.entity.Student;
import org.apache.ibatis.annotations.Mapper;

public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

mapper文件

<?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.liuhaiyang.springboot.dao.StudentMapper">

<!--  resultMap作用: 1.当数据库中字段名称与实体类对象的属性名不一致时,可以进行转换
      2.当前查询的结果没有对象一个表的时候,可以自定义一个结果集-->
  <resultMap id="BaseResultMap" type="com.liuhaiyang.springboot.entity.Student">
<!--    id 标签只能修饰主键字段   result:除了主键以外的字段
        column数据库中的字段名称   property映射对象属性名称   jdbcType 列中数据库中字段的类型(可以省略)
        数据库表字段名 user_name    对应得实体对象属性名 username
        如果数据库字段名称由多个单词构成,通过MyBatis逆向工程生成的对象属性名称 会按照驼峰命名法则生成属性名称
          其中: 数据库字段名称由多个单词构成的时候必须使用_下划线分隔-->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>

<!--  sql语句片段  通过include标签引用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="com.liuhaiyang.springboot.entity.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>

  <insert id="insertSelective" parameterType="com.liuhaiyang.springboot.entity.Student">
    insert into t_student
        <!--suffixOverrides 去除多余的逗号-->
    <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="com.liuhaiyang.springboot.entity.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="com.liuhaiyang.springboot.entity.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

</mapper>

1.5 service、controller、启动类

拿一个简单的看一下,重点是GeneratorMapper.xml逆向生成文件的理解

package com.liuhaiyang.springboot.service;

import com.liuhaiyang.springboot.entity.Student;

public interface StudentService {
    Student findStudent(Integer id);
}
package com.liuhaiyang.springboot.service.Impl;

import com.liuhaiyang.springboot.dao.StudentMapper;
import com.liuhaiyang.springboot.entity.Student;
import com.liuhaiyang.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired(required = false)
    private StudentMapper studentMapper;
//    @Transactional  表示添加事务,当方法异常时回滚
    @Override
    public Student findStudent(Integer id) {
        Student student=studentMapper.selectByPrimaryKey(id);
//        int a=10/0;
        return student;
    }
}
package com.liuhaiyang.springboot.controller;

import com.liuhaiyang.springboot.entity.Student;
import com.liuhaiyang.springboot.service.StudentService;
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;

@Controller
public class StudentController {
    @Autowired(required = false)
    private StudentService studentService;
    @ResponseBody
    @RequestMapping("/student")
    public Object studentcontroller(Integer id){
        Student student=studentService.findStudent(id);
        return student;
    }
}
package com.liuhaiyang.springboot;

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

@SpringBootApplication
@MapperScan(basePackages = "com.liuhaiyang.spring.dao")   //开启扫描Mapper接口的包以及子目录  basePackages可以省略
//@EnableTransactionManagement 开启事务
public class SpringbootTest05Application {

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

}

结果截图:

2 DAO 其它开发方式

将Dao接口添加到容器的方式有两种,一种是在Dao接口上添加添加@Mapper,第二种是在启动类上添加@MapperScan

2.1 Dao接口上添加添加@Mapper

这种方式很简单,只需要在Dao接口上添加添加@Mapper,就没了,以上面代码为例

package com.liuhaiyang.springboot.dao;

import com.liuhaiyang.springboot.entity.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper //扫描DAo接口到spring容器
public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

2.2 在启动类上添加@MapperScan

这个方式相比于上面的方式,有点复杂,但是也是很简单,首先,在启动类上添加@MapperScan注解,正常情况下,我们还需要手动将mapper.xml文件添加到编译好的文价下面,当然,如果编译结果含有mapper.xml文件,则不需要。

package com.liuhaiyang.springboot;

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

@SpringBootApplication
@MapperScan(basePackages = "com.liuhaiyang.spring.dao")   //开启扫描Mapper接口的包以及子目录  basePackages可以省略
//@EnableTransactionManagement 开启事务
public class SpringbootTest05Application {

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

}

 在接口和映射文件不在同一个包的情况下,还需要在 application.properties 配置文件中指定映射文件的位置。


#指定MyBatis映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值