您的位置:首页 > 科技 > IT业 > 推广英文_国家企业查询系统官网天眼查_推广关键词排名_今日新闻联播主要内容

推广英文_国家企业查询系统官网天眼查_推广关键词排名_今日新闻联播主要内容

2025/3/16 6:42:32 来源:https://blog.csdn.net/m0_74825678/article/details/146159463  浏览:    关键词:推广英文_国家企业查询系统官网天眼查_推广关键词排名_今日新闻联播主要内容
推广英文_国家企业查询系统官网天眼查_推广关键词排名_今日新闻联播主要内容

Spring Boot与MyBatis的配置

一、简介

Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架,它简化了Spring应用的初始搭建以及开发过程。MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。将Spring Boot和MyBatis结合使用,可以高效地开发数据驱动的应用程序。

二、环境准备

(一)创建Spring Boot项目
  1. 可以使用Spring Initializr(https://start.spring.io/)来创建一个基础的Spring Boot项目。
    • 在创建项目时,选择合适的项目元数据,如项目的Group和Artifact等信息。
    • 可以选择添加一些常用的依赖,如Web依赖(如果项目需要提供Web服务)等。不过,对于MyBatis的集成,初始创建时不需要专门添加MyBatis相关依赖,我们后续手动添加。
  2. 下载生成的项目压缩包并解压到本地开发环境。
(二)添加MyBatis依赖
  1. 在项目的pom.xml(如果是Maven项目)中添加MyBatis和相关数据库驱动的依赖。
    • 对于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>
      

三、数据库配置

(一)配置数据源
  1. 在Spring Boot的配置文件(application.properties或者application.yml)中配置数据源相关信息。
    • 如果使用application.properties:

      spring.datasource.url = jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTC
      spring.datasource.username = root
      spring.datasource.password = your_password
      spring.datasource.driver - class - name = com.mysql.cj.jdbc.Driver
      
    • 如果使用application.yml:

      spring:datasource:url: jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTCusername: rootpassword: your_passworddriver - class - name: com.mysql.cj.jdbc.Driver
      

四、MyBatis配置

(一)实体类创建
  1. 根据数据库表结构创建对应的实体类。例如,如果有一个名为“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接口:

      @Mapper
      public interface UserMapper {User selectUserById(Integer id);int insertUser(User user);int updateUser(User user);int deleteUserById(Integer id);
      }
      
    • 这里的@Mapper注解(如果使用注解方式)用于将该接口标记为MyBatis的Mapper接口,这样Spring Boot就能够识别并自动创建该接口的代理实现。

(三)Mapper XML文件创建(如果使用XML方式)
  1. 如果不使用注解方式编写SQL语句,而是使用XML文件,则需要创建Mapper XML文件。
    • 在resources/mapper目录下创建UserMapper.xml(假设项目采用的是Maven的标准目录结构)。

    • 内容如下:

      <?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接口的全限定名相同。

(四)配置MyBatis扫描路径
  1. 如果使用XML方式的Mapper文件,需要在Spring Boot配置文件中配置MyBatis的Mapper扫描路径。
    • 在application.properties中:

      mybatis.mapper - locations = classpath:mapper/*.xml
      
    • 在application.yml中:

      mybatis:mapper - locations: classpath:mapper/*.xml
      

五、使用MyBatis进行数据操作

(一)在Service层调用Mapper方法
  1. 创建一个UserService类来调用UserMapper中的方法。
    • 例如:

      @Service
      public class UserService {@Autowiredprivate 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中的数据操作方法。

(二)在Controller层调用Service方法(如果是Web应用)
  1. 创建一个UserController类(假设是一个Web应用,需要提供RESTful接口等)。

    @RestController
    public class UserController {@Autowiredprivate 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请求到数据操作的完整流程。

六、事务管理

  1. 在Spring Boot中管理MyBatis的事务非常方便。
    • 如果要在某个Service方法上添加事务管理,可以使用@Transactional注解。例如:

      @Service
      public class UserService {@Autowiredprivate UserMapper userMapper;@Transactionalpublic int addUser(User user) {// 一些业务逻辑判断等操作int result = userMapper.insertUser(user);// 如果插入成功后还有其他操作,如更新相关联的数据等return result;}
      }
      
    • 这样,如果在addUser方法中的任何一个数据库操作出现异常,整个事务都会回滚,保证数据的一致性。

七、高级配置

(一)配置MyBatis的缓存
  1. MyBatis提供了一级缓存和二级缓存。
    • 一级缓存是基于SqlSession的,默认是开启的。

    • 二级缓存可以通过在Mapper接口或者Mapper XML文件中配置开启。

    • 在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>
      
    • 这里的标签用于配置二级缓存的相关属性,如缓存的清除策略(eviction)、刷新间隔(flushInterval)、缓存大小(size)和是否只读(readOnly)等。

(二)配置MyBatis的插件
  1. MyBatis允许使用插件来扩展其功能。例如,可以使用PageHelper插件来实现分页功能。
    • 首先添加PageHelper的依赖:

      <dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper - spring - boot - starter</artifactId><version>1.3.0</version>
      </dependency>
      
    • 然后在配置文件中进行简单配置(以application.yml为例):

      pagehelper:helper - dialect: mysqlreasonable: truesupport - methods - arguments: true
      
    • 在使用分页查询时,在Mapper接口方法调用之前使用PageHelper.startPage方法即可。例如:

      public class UserService {@Autowiredprivate UserMapper userMapper;public List<User> getUsersByPage(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);return userMapper.selectAllUsers();}
      }
      

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com