十七springboot2核心技术——整合mybatis(代码片段)

上善若水 上善若水     2022-12-20     218

关键词:

整合mybatis

1.1、添加mybatis、数据库驱动依赖

<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整合springboot框架的起步依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>$mybatis-spring.version</version>
    </dependency>
</dependencies>

1.2、编写pojo、controller、service、mapper层代码


Student.java

package com.xbmu.pojo;

public class Student 
    private Integer id;
    private String name;
    private Integer age;
    /* 省略set 与 get 方法 */

StudentController.java

package com.xbmu.controller;

import com.xbmu.pojo.Student;
import com.xbmu.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
    private StudentService studentService;

    @RequestMapping("/findStuById")
    public @ResponseBody Object findStuById(Integer id)
        Student student = studentService.findStuById(id);
        return student;
    

StudentService.java

package com.xbmu.service;

import com.xbmu.pojo.Student;

public interface StudentService 
    Student findStuById(Integer id);

StudentServiceImpl.java

package com.xbmu.service.impl;

import com.xbmu.pojo.Student;
import com.xbmu.service.StudentService;
import com.xbmu.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService 

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student findStuById(Integer id) 
        return studentMapper.findStuById(id);
    

StudentMapper.java

package com.xbmu.mapper;

import com.xbmu.pojo.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper // 扫描dao接口到spring容器
public interface StudentMapper 
    Student findStuById(Integer id);

StudentMapper.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.xbmu.mapper.StudentMapper">
    <select id="findStuById" parameterType="java.lang.Integer" resultType="com.xbmu.pojo.Student">
        SELECT id,name,age FROM t_student
        <where>
            id = #id
        </where>
    </select>
</mapper>

1.3、spring核心配置文件

# springboot核心配置文件
# 指定内嵌 tomcat 端口号
server:
  port: 8080
  servlet:
    context-path: / # 指定上下文根,默认 /

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

1.4、手动指定资源文件夹

默认情况下,Mybatis 的 xml 映射文件不会编译到 target 的 class 目录下,所以我们需要在 pom.xml 文件中配置 resource。

<build>
   <!--
        手动指定文件夹为resources
    -->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
    <!--springboot编译打包插件-->
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

1.5、启动,运行访问

1.6、@Mappper 、@MapperScan(basePackages = “包名”)

@Mapper作用:mybatis 自动扫描数据持久层的映射文件及 dao 接口的关系。需要在每一个Mapper接口类上添加,作用扫描dao接口。
@MapperScan(basePackages = "包名")作用:是在springboot启动入口类上添加的,它是扫描所有的包。
MainApplication.java

package com.xbmu;

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

@SpringBootApplication
@MapperScan(basePackages = "com.xbmu.mapper")
public class MainApplication 
    public static void main(String[] args) 
        SpringApplication.run(MainApplication.class,args);
    

如果在springboot启动入口类上配置了@MapperScan注解,就不需要再在每个mapper接口上配置@Mapper注解了。

1.7、Mapper映射文件的存放位置

关于Mapper映射文件存放的位置的写法有以下两种:
1.将Mapper接口和Mapper映射文件存放到 src/main/java同一目录下,还需要在pom文件中手动指定资源文件夹路径resources

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

2.将Mapper接口和Mapper映射文件分开存放
Mapper接口类存放到src/main/java目录下;
Mapper映射文件存放到resources(类路径)

1.8、Mapper映射文件存放到resources(类路径)

因为springboot不能自动编译接口映射的xml文件,还需要手动在pom文件中指定,所以有的公司直接将映射文件放到resources目录下。

  • 在resources目录下新建目录mapper存放映射文件,将StudentMapper.xml文件移到resources/mapper目录下
  • 在application.yml配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定
# 指定mybatis映射文件的路径
mybatis:
  mapper-locations: classpath:mapper/*.xml

MainApplication.java

package com.xbmu;

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

@SpringBootApplication
@MapperScan(basePackages = "com.xbmu.mapper")
public class MainApplication 
    public static void main(String[] args) 
        SpringApplication.run(MainApplication.class,args);
    

1.9、SpringBoot事务支持

SpringBoot使用事务非常简单,底层依然采用的是spring本身提供的事务管理。

  • 在入口类中使用注解@EnableTransactionManagement开启事务支持。

@EnableTransactionManagement 可选,但是 业务方法上 必须添加@Transactional

package com.xbmu;

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.xbmu.mapper") // 开启扫描mapper接口的包以及子包
@EnableTransactionManagement //开启事务支持(可选项,但@Transactional 必须添加)
public class MainApplication 
    public static void main(String[] args) 
        SpringApplication.run(MainApplication.class,args);
    

  • 在访问数据库的service类或方法上添加注解@Transactional即可。
package com.xbmu.service.impl;

import com.xbmu.pojo.Student;
import com.xbmu.service.StudentService;
import com.xbmu.mapper.StudentMapper;
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
    private StudentMapper studentMapper;
    
    @Override
    @Transactional //添加此注解说明该方法添加的事务管理
    public Integer updateStuById(Student student) 
        Integer rows = studentMapper.updateStuById(student);
        //在此构造一个除数为 0 的异常,测试事务是否起作用
        int i = 10 / 0;
        return rows;
    

十六springboot2核心技术——整合jsp(代码片段)

一、整合jsp1.1、添加依赖<dependencies><!--springboot整合web框架起步依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId&g 查看详情

十六springboot2核心技术——整合jsp(代码片段)

一、整合jsp1.1、添加依赖<dependencies><!--springboot整合web框架起步依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId&g 查看详情

十九springboot2核心技术——整合alibabadubbo(代码片段)

一、SpringBoot整合AlibabaDubbo参考连接:企业级SpringBoot与Dubbo的并用1.1、项目工程、添加依赖1.2、添加AlibabaDubbo依赖<dependencies><!--接口工程--><dependency><groupId>com.xbmu</groupId><artifactI 查看详情

十九springboot2核心技术——整合alibabadubbo(代码片段)

一、SpringBoot整合AlibabaDubbo参考连接:企业级SpringBoot与Dubbo的并用1.1、项目工程、添加依赖1.2、添加AlibabaDubbo依赖<dependencies><!--接口工程--><dependency><groupId>com.xbmu</groupId><artifactI 查看详情

二十一springboot2核心技术——整合activiti7(代码片段)

...、Activiti7与SpringBoot整合Activiti7发布正式版之后,它与SpringBoot2.x已经完全支持整合开发。1.1、SpringBoot整合Activiti7的配置为了能够实现SpringBoot与Activiti7整合开发,首先我们要引入相关的依赖支持。在工程的pom.xml文件中引入... 查看详情

二十springboot2核心技术——整合logback(代码片段)

一、SpringBoot整合logback1.1、日志文件SpringBoot官方推荐优先使用带有-spring的文件名作为你的日志配置(如使用logback-spring.xml,而不是logback.xml),命令为logback-spring.xml的日志配置文件。默认的命名规则,并且放... 查看详情

二十springboot2核心技术——整合logback(代码片段)

一、SpringBoot整合logback1.1、日志文件SpringBoot官方推荐优先使用带有-spring的文件名作为你的日志配置(如使用logback-spring.xml,而不是logback.xml),命令为logback-spring.xml的日志配置文件。默认的命名规则,并且放... 查看详情

十八springboot2核心技术——整合redis(代码片段)

SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情

十八springboot2核心技术——整合redis(代码片段)

SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情

springboot2系列教程(十七)|整合websocket实现聊天室

微信公众号:一个优秀的废人。如有问题,请后台留言,反正我也不会听。前言昨天那篇介绍了WebSocket实现广播,也即服务器端有消息时,将消息发送给所有连接了当前endpoint的浏览器。但这无法解决消息由谁发送,又由谁接收... 查看详情

rabbitmq核心概念及与springboot2的整合

RabbitMQ简介RabbitMQ是什么RabbitMQ是一个用Erlang编写的开源的消息队列中间件,它实现了AMQP协议(其实还实现了MTQQ等消息协议)。和其他两个主流的消息队列中间件Kafka和RocketMQ相比,拥有更低的延迟、更高的稳定性、更完备的功能... 查看详情

springboot2核心技术(基础入门)-02springboot2入门安装配置

...:GettingStarted【Maven已安装】学习资料文档地址:SpringBoot2核心技术与响应式编程·语雀文档不支持旧版本IE、Edge浏览器,请使用chrome或者firefox视频地址:谷粒学苑-Jav 查看详情

springboot2.0整合springsecurity前后端分离进行自定义权限控制

  在阅读本文之前可以先看看springsecurity的基本执行流程,下面我展示一些核心配置文件,后面给出完整的整合代码到git上面,有兴趣的小伙伴可以下载进行研究  使用maven工程构建项目,首先需要引入最核心的依赖,<depe... 查看详情

springboot2.0深度实践之核心技术篇

第1章系列总览总览SpringBoot2.0深度实践系列课程的整体议程,包括SpringBoot三大核心特性(组件自动装配、嵌入式Web容?、生产准备特性)、Web应用(传统Servlet、SpringWebMVC、SpringWebFlux)、数据相关(JDBC、JPA、事务)、功能扩展(Sp... 查看详情

springboot2基于springboot实现ssmp整合(代码片段)

前言​    重头戏来了,SpringBoot之所以好用,就是它能方便快捷的整合其他技术,本文讲解一些技术的整合方式,通过这本文的学习,感受SpringBoot到底有多酷炫。本文学习如下技术的整合方式整合JUnit整... 查看详情

springboot2.0之整合apollo

SpringBoot客户端对接阿波罗服务器端  核心源码都在这个压缩包里面封装好了环境运行shell脚本就ok了  下面进入到本地maven仓库:远程仓库apollo的jar包只能打包到本地或者公司的私服了 首先引入pom:<parent> &... 查看详情

springboot2.x版本整合redis集群

参考技术A启动Redis集群搭建方式SpringBoot1.x版本默认使用jedis连接,2.x版本使用lettuce连接ymlyml测试 查看详情

springboot2整合ehcache组件,轻量级缓存管理

“智慧展厅中控系统软件”是打造智慧展厅所需的技术,能够有效的满足新时代社会科技文化发展的过程中,计算机软件技术的开发,实现了中控系统技术开发效果,营造智慧展厅发展,所具有的互动发展效果,是一款能够运用... 查看详情