存储过程以及高级映射

发布时间:2025-06-24 18:01:54  作者:北方职教升学中心  阅读量:728


不过,对于MyBatis的集成,初始创建时不需要专门添加MyBatis相关依赖,我们后续手动添加。环境准备

(一)创建Spring Boot项目

  1. 可以使用Spring Initializr(https://start.spring.io/)来创建一个基础的Spring Boot项目。例如:
    @Servicepublic class UserService {    @Autowired    private UserMapper userMapper;    @Transactional    public int addUser(User user) {        // 一些业务逻辑判断等操作        int result = userMapper.insertUser(user);        // 如果插入成功后还有其他操作,如更新相关联的数据等        return result;    }}
  2. 这样,如果在addUser方法中的任何一个数据库操作出现异常,整个事务都会回滚,保证数据的一致性。基于Spring的生产级应用程序的框架,它简化了Spring应用的初始搭建以及开发过程。

(二)添加MyBatis依赖

  1. 在项目的pom.xml(如果是Maven项目)中添加MyBatis和相关数据库驱动的依赖。

    二、例如:
    public class UserService {    @Autowired    private UserMapper userMapper;    public List<User> getUsersByPage(int pageNum, int pageSize) {        PageHelper.startPage(pageNum, pageSize);        return userMapper.selectAllUsers();    }}

通过以上的配置和操作步骤,就可以在Spring Boot项目中成功地集成和使用MyBatis进行高效的数据持久化操作,无论是简单的CRUD操作还是涉及到高级功能如事务管理、

MyBatis是一款优秀的持久层框架,它支持定制化SQL、
  • 如果要在某个Service方法上添加事务管理,可以使用@Transactional注解。
  • 内容如下:
    <?xml version="1.0" encoding="UTF - 8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis - 3.dtd"><mapper namespace="com.example.demo.mapper.UserMapper">    <select id="selectUserById" resultMap="userResultMap">        SELECT * FROM user WHERE id = #{id}    </select>    <insert id="insertUser">        INSERT INTO user (username, password) VALUES (#{username}, #{password})    </insert>    <update id="updateUser">        UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}    </update>    <delete id="deleteUserById">        DELETE FROM user WHERE id = #{id}    </delete>    <resultMap id="userResultMap" type="com.example.demo.entity.User">        <id property="id" column="id"/>        <result property="username" column="username"/>        <result property="password" column="password"/>    </resultMap></mapper>
  • 这里的namespace属性的值要与对应的Mapper接口的全限定名相同。

(三)Mapper XML文件创建(如果使用XML方式)

  1. 如果不使用注解方式编写SQL语句,而是使用XML文件,则需要创建Mapper XML文件。例如,可以使用PageHelper插件来实现分页功能。
    • 对于MyBatis本身:
      <dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis - spring - boot - starter</artifactId>    <version>2.2.2</version></dependency>
    • 如果使用MySQL数据库,添加MySQL驱动依赖:
      <dependency>    <groupId>mysql</groupId>    <artifactId>mysql - connector - java</artifactId>    <version>8.0.26</version></dependency>

三、缓存和插件的使用等。

(二)配置MyBatis的插件

  1. MyBatis允许使用插件来扩展其功能。
    • 在application.properties中:
      mybatis.mapper - locations = classpath:mapper/*.xml
    • 在application.yml中:
      mybatis:  mapper - locations: classpath:mapper/*.xml

五、

七、
  • 在resources/mapper目录下创建UserMapper.xml(假设项目采用的是Maven的标准目录结构)。例如,如果有一个名为“user”的表,结构如下:
    CREATE TABLE user (    id INT PRIMARY KEY AUTO_INCREMENT,    username VARCHAR(50),    password VARCHAR(50));
    • 对应的Java实体类为:
      public class User {    private Integer id;    private String username;    private String password;    // 生成getter和setter方法    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}
  • (二)Mapper接口创建

    1. 创建Mapper接口来定义与数据库交互的方法。
      • 例如,创建一个UserMapper接口:
        @Mapperpublic interface UserMapper {    User selectUserById(Integer id);    int insertUser(User user);    int updateUser(User user);    int deleteUserById(Integer id);}
      • 这里的@Mapper注解(如果使用注解方式)用于将该接口标记为MyBatis的Mapper接口,这样Spring Boot就能够识别并自动创建该接口的代理实现。
        • 首先添加PageHelper的依赖:
          <dependency>    <groupId>com.github.pagehelper</groupId>    <artifactId>pagehelper - spring - boot - starter</artifactId>    <version>1.3.0</version></dependency>
        • 然后在配置文件中进行简单配置(以application.yml为例):
          pagehelper:  helper - dialect: mysql  reasonable: true  support - methods - arguments: true
        • 在使用分页查询时,在Mapper接口方法调用之前使用PageHelper.startPage方法即可。将Spring Boot和MyBatis结合使用,可以高效地开发数据驱动的应用程序。
          • 一级缓存是基于SqlSession的,默认是开启的。
          • 二级缓存可以通过在Mapper接口或者Mapper XML文件中配置开启。数据库配置

(一)配置数据源

  1. 在Spring Boot的配置文件(application.properties或者application.yml)中配置数据源相关信息。高级配置

    (一)配置MyBatis的缓存

    1. MyBatis提供了一级缓存和二级缓存。事务管理
      1. 在Spring Boot中管理MyBatis的事务非常方便。
        • 如果使用application.properties:
          spring.datasource.url = jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTCspring.datasource.username = rootspring.datasource.password = your_passwordspring.datasource.driver - class - name = com.mysql.cj.jdbc.Driver
        • 如果使用application.yml:
          spring:  datasource:    url: jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTC    username: root    password: your_password    driver - class - name: com.mysql.cj.jdbc.Driver

      四、刷新间隔(flushInterval)、缓存大小(size)和是否只读(readOnly)等。MyBatis配置

      (一)实体类创建

      1. 根据数据库表结构创建对应的实体类。

      六、

    2. 在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.dtd"><mapper namespace="com.example.demo.mapper.UserMapper">    <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>    <!-- 其他SQL语句定义等 --></mapper>
    3. 这里的<cache>标签用于配置二级缓存的相关属性,如缓存的清除策略(eviction)、
      • 例如:
        @Servicepublic class UserService {    @Autowired    private UserMapper userMapper;    public User getUserById(Integer id) {        return userMapper.selectUserById(id);    }    public int addUser(User user) {        return userMapper.insertUser(user);    }    public int updateUserInfo(User user) {        return userMapper.updateUser(user);    }    public int deleteUser(int id) {        return userMapper.deleteUserById(id);    }}
      • 这里通过@Autowired注解注入UserMapper实例,然后就可以在Service方法中调用Mapper中的数据操作方法。存储过程以及高级映射。

        Spring Boot与MyBatis的配置

        一、使用MyBatis进行数据操作

        (一)在Service层调用Mapper方法

        1. 创建一个UserService类来调用UserMapper中的方法。

    (二)在Controller层调用Service方法(如果是Web应用)

    1. 创建一个UserController类(假设是一个Web应用,需要提供RESTful接口等)。
    2. 下载生成的项目压缩包并解压到本地开发环境。
      @RestControllerpublic class UserController {    @Autowired    private UserService userService;    @GetMapping("/user/{id}")    public User getUserById(@PathVariable("id") Integer id) {        return userService.getUserById(id);    }    @PostMapping("/user")    public int addUser(@RequestBody User user) {        return userService.addUser(user);    }    @PutMapping("/user")    public int updateUser(@RequestBody User user) {        return userService.updateUserInfo(user);    }    @DeleteMapping("/user/{id}")    public int deleteUser(@PathVariable("id") Integer id) {        return userService.deleteUser(id);    }}
      • 这里同样通过@Autowired注解注入UserService实例,然后在Controller的各个方法中调用Service方法,实现了从Web请求到数据操作的完整流程。
        • 在创建项目时,选择合适的项目元数据,如项目的Group和Artifact等信息。简介

          Spring Boot是一个用于创建独立的、

    (四)配置MyBatis扫描路径

    1. 如果使用XML方式的Mapper文件,需要在Spring Boot配置文件中配置MyBatis的Mapper扫描路径。
    2. 可以选择添加一些常用的依赖,如Web依赖(如果项目需要提供Web服务)等。