当前位置: 首页 > news >正文

Spring Boot数据访问篇:整合MyBatis操作数据库

Spring Boot数据访问篇:整合MyBatis操作数据库

在前面的文章中,我们介绍了Spring Boot的基本概念、配置管理等内容。在实际的Web应用开发中,数据访问是一个核心环节。MyBatis作为Java世界中最受欢迎的持久层框架之一,与Spring Boot的整合可以大大简化数据库操作。本文将详细介绍如何在Spring Boot项目中整合MyBatis进行数据访问操作。

MyBatis简介

MyBatis是一个优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。MyBatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs(Plain Old Java Objects)映射成数据库中的记录。

MyBatis的主要优点包括:

  1. 简单易学,学习成本低
  2. 灵活,SQL写在XML里,便于统一管理和优化
  3. 解除SQL与程序代码的耦合
  4. 提供映射标签,支持对象与数据库的ORM字段关系映射
  5. 提供对象关系映射标签,支持对象关系组件维护

创建Spring Boot项目并添加MyBatis依赖

首先,我们创建一个Spring Boot项目并添加MyBatis相关依赖。在pom.xml中添加以下依赖:

4.0.0org.springframework.bootspring-boot-starter-parent2.7.0com.examplespringboot-mybatis-demo1.0.0springboot-mybatis-demoSpring Boot整合MyBatis示例8org.springframework.bootspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.2.2mysqlmysql-connector-javaruntimeorg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-maven-plugin

配置数据库连接

在application.yml中配置数据库连接信息:

spring:datasource:url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver# MyBatis配置
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.entityconfiguration:map-underscore-to-camel-case: true

创建实体类

创建一个用户实体类User:

package com.example.entity;public class User {private Long id;private String name;private Integer age;private String email;// 构造方法public User() {}public User(String name, Integer age, String email) {this.name = name;this.age = age;this.email = email;}// Getter和Setter方法public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + ''' +", age=" + age +", email='" + email + ''' +'}';}
}

创建Mapper接口

创建UserMapper接口:

package com.example.mapper;import com.example.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;@Mapper
public interface UserMapper {/*** 插入用户*/@Insert("INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})")@Options(useGeneratedKeys = true, keyProperty = "id")int insert(User user);/*** 根据ID查询用户*/@Select("SELECT id, name, age, email FROM user WHERE id = #{id}")User selectById(Long id);/*** 查询所有用户*/@Select("SELECT id, name, age, email FROM user")List selectAll();/*** 更新用户信息*/@Update("UPDATE user SET name = #{name}, age = #{age}, email = #{email} WHERE id = #{id}")int update(User user);/*** 根据ID删除用户*/@Delete("DELETE FROM user WHERE id = #{id}")int deleteById(Long id);
}

使用XML配置Mapper

除了使用注解方式,我们也可以使用XML文件来配置Mapper。首先创建UserMapper.xml文件:

INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})SELECT id, name, age, email FROM user WHERE id = #{id}SELECT id, name, age, email FROM userUPDATE user SET name = #{name}, age = #{age}, email = #{email} WHERE id = #{id}DELETE FROM user WHERE id = #{id}SELECT id, name, age, email FROM user WHERE name LIKE CONCAT('%', #{name}, '%')

对应的Mapper接口方法:

package com.example.mapper;import com.example.entity.User;
import java.util.List;@Mapper
public interface UserMapper {// 注解方式的方法...// XML方式的方法int insertUser(User user);User selectUserById(Long id);List selectAllUsers();int updateUser(User user);int deleteUserById(Long id);List selectUsersByName(String name);
}

创建Service层

创建UserService接口和实现类:

package com.example.service;import com.example.entity.User;
import java.util.List;public interface UserService {User createUser(User user);User getUserById(Long id);List getAllUsers();User updateUser(User user);void deleteUserById(Long id);List getUsersByName(String name);
}
package com.example.service.impl;import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User createUser(User user) {userMapper.insert(user);return user;}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic List getAllUsers() {return userMapper.selectAll();}@Overridepublic User updateUser(User user) {userMapper.update(user);return user;}@Overridepublic void deleteUserById(Long id) {userMapper.deleteById(id);}@Overridepublic List getUsersByName(String name) {return userMapper.selectUsersByName(name);}
}

创建Controller层

创建UserController:

package com.example.controller;import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;/*** 创建用户*/@PostMappingpublic User createUser(@RequestBody User user) {return userService.createUser(user);}/*** 根据ID获取用户*/@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}/*** 获取所有用户*/@GetMappingpublic List getAllUsers() {return userService.getAllUsers();}/*** 更新用户*/@PutMappingpublic User updateUser(@RequestBody User user) {return userService.updateUser(user);}/*** 删除用户*/@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUserById(id);}/*** 根据名称搜索用户*/@GetMapping("/search")public List searchUsers(@RequestParam String name) {return userService.getUsersByName(name);}
}

创建主应用类

创建Spring Boot主应用类:

package com.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringBootMyBatisApplication {public static void main(String[] args) {SpringApplication.run(SpringBootMyBatisApplication.class, args);}
}

数据库表结构

创建user表:

CREATE TABLE user (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,age INT,email VARCHAR(100)
);

测试接口

启动应用后,可以使用以下API进行测试:

  1. 创建用户:

    POST http://localhost:8080/users
    Content-Type: application/json{"name": "张三","age": 25,"email": "zhangsan@example.com"
    }
    
  2. 获取用户:

    GET http://localhost:8080/users/1
    
  3. 获取所有用户:

    GET http://localhost:8080/users
    
  4. 更新用户:

    PUT http://localhost:8080/users
    Content-Type: application/json{"id": 1,"name": "张三丰","age": 30,"email": "zhangsanfeng@example.com"
    }
    
  5. 删除用户:

    DELETE http://localhost:8080/users/1
    
  6. 搜索用户:

    GET http://localhost:8080/users/search?name=张
    

MyBatis高级特性

1. 分页查询

使用PageHelper插件实现分页查询:

添加依赖:

com.github.pagehelperpagehelper-spring-boot-starter1.4.2

在Service中使用分页:

@Override
public PageInfo getUsersByPage(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);List users = userMapper.selectAll();return new PageInfo<>(users);
}

2. 动态SQL

在XML中使用动态SQL:

SELECT id, name, age, email FROM userAND name LIKE CONCAT('%', #{name}, '%')AND age = #{age}

3. 批量操作

批量插入用户:

INSERT INTO user(name, age, email) VALUES(#{user.name}, #{user.age}, #{user.email})

最佳实践

  1. 使用Mapper接口注解:对于简单的CRUD操作,可以使用注解方式,代码更简洁。

  2. 复杂SQL使用XML:对于复杂的SQL语句,建议使用XML配置,便于维护和优化。

  3. 合理使用事务:在Service层使用@Transactional注解管理事务。

  4. 避免N+1查询问题:合理设计查询,避免循环查询数据库。

  5. SQL优化:注意SQL语句的优化,添加合适的索引。

  6. 连接池配置:合理配置数据库连接池参数。

总结

本文详细介绍了如何在Spring Boot项目中整合MyBatis进行数据访问操作。我们学习了:

  1. MyBatis的基本概念和优势
  2. 如何在Spring Boot中添加MyBatis依赖
  3. 数据库连接配置
  4. 实体类、Mapper接口和XML配置的创建
  5. Service层和Controller层的实现
  6. MyBatis的高级特性和最佳实践

通过整合Spring Boot和MyBatis,我们可以快速构建功能完善的Web应用,同时享受两者带来的便利。在下一篇文章中,我们将介绍如何构建RESTful API。

作者:CSDN博客助手
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。

http://www.dtcms.com/a/549850.html

相关文章:

  • 丰都网站建设报价现代示范校建设专题网站
  • Flink Keyed State 详解之七
  • 中国建设银行贵州分行网站宁波建设银行管方网站
  • NVIDIA驱动更新“翻车”?解决RTX 2060在Bilibili客户端无法加载4K视频的终极指南*
  • 贵德县建设局网站校园兼职网站开发用例图
  • JavaSE知识分享——类和对象(下)
  • 企业级K8s部署:Helm+Kustomize混合策略实现零配置漂移与10分钟多环境发布
  • 上海人才中心昆明网站词排名优化
  • jQuery Growl - 实用且易于集成的通知插件
  • Manage Provisioning Access 功能详解
  • 龙岗在线网站建设网络销售网站外包
  • NVIDIA NCCL 源码学习(十六)- nccl的ibgda(GIN)
  • 深度优先搜索(DFS)
  • 协会网站建设方案wordpress 以前文章灯箱
  • PCIe学习笔记
  • 处理 rstudio-server 卡死问题
  • C 盘清理技巧分享
  • 零基础小白如何高效入门项目管理?
  • 安装与切换Rust版本
  • 云服务器建立多个网站文山知名网站建设公司
  • 深圳网站建设网站制作网站推广vps一键安装wordpress
  • 定制网站和模板建站室内设计培训网课
  • 云免网站空间自己怎么做网站模块
  • 佰力博检测与您探讨压电薄膜介电温谱测试的目的
  • 所有权转移在函数调用中的表现:Rust 内存安全的函数边界管理
  • WebRTC学习中各项概念笔记
  • 外包网站问些什么问题一个网站可以做几级链接
  • 网站开发商怎么关闭图片显示上海网站外包
  • K8s练习
  • 订阅飞书审批事件