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的主要优点包括:
- 简单易学,学习成本低
- 灵活,SQL写在XML里,便于统一管理和优化
- 解除SQL与程序代码的耦合
- 提供映射标签,支持对象与数据库的ORM字段关系映射
- 提供对象关系映射标签,支持对象关系组件维护
创建Spring Boot项目并添加MyBatis依赖
首先,我们创建一个Spring Boot项目并添加MyBatis相关依赖。在pom.xml中添加以下依赖:
            
            
              xml
              
              
            
          
              4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.0
        
    
    com.example
    springboot-mybatis-demo
    1.0.0
    springboot-mybatis-demo
    Spring Boot整合MyBatis示例
    
        8
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.2
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    配置数据库连接
在application.yml中配置数据库连接信息:
            
            
              yaml
              
              
            
          
          spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
# MyBatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.entity
  configuration:
    map-underscore-to-camel-case: true创建实体类
创建一个用户实体类User:
            
            
              java
              
              
            
          
          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;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", age=" + age +
                ", email='" + email + ''' +
                '}';
    }
}创建Mapper接口
创建UserMapper接口:
            
            
              java
              
              
            
          
          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文件:
            
            
              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 user
    
    
    
    
        UPDATE 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接口方法:
            
            
              java
              
              
            
          
          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接口和实现类:
            
            
              java
              
              
            
          
          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);
}
            
            
              java
              
              
            
          
          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 {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public User createUser(User user) {
        userMapper.insert(user);
        return user;
    }
    
    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public List getAllUsers() {
        return userMapper.selectAll();
    }
    
    @Override
    public User updateUser(User user) {
        userMapper.update(user);
        return user;
    }
    
    @Override
    public void deleteUserById(Long id) {
        userMapper.deleteById(id);
    }
    
    @Override
    public List getUsersByName(String name) {
        return userMapper.selectUsersByName(name);
    }
}创建Controller层
创建UserController:
            
            
              java
              
              
            
          
          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 {
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建用户
     */
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    /**
     * 获取所有用户
     */
    @GetMapping
    public List getAllUsers() {
        return userService.getAllUsers();
    }
    
    /**
     * 更新用户
     */
    @PutMapping
    public 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主应用类:
            
            
              java
              
              
            
          
          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表:
            
            
              sql
              
              
            
          
          CREATE TABLE user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    age INT,
    email VARCHAR(100)
);测试接口
启动应用后,可以使用以下API进行测试:
- 
创建用户: POST http://localhost:8080/users Content-Type: application/json { "name": "张三", "age": 25, "email": "zhangsan@example.com" }
- 
获取用户: GET http://localhost:8080/users/1
- 
获取所有用户: GET http://localhost:8080/users
- 
更新用户: PUT http://localhost:8080/users Content-Type: application/json { "id": 1, "name": "张三丰", "age": 30, "email": "zhangsanfeng@example.com" }
- 
删除用户: DELETE http://localhost:8080/users/1
- 
搜索用户: GET http://localhost:8080/users/search?name=张
MyBatis高级特性
1. 分页查询
使用PageHelper插件实现分页查询:
添加依赖:
            
            
              xml
              
              
            
          
              com.github.pagehelper
    pagehelper-spring-boot-starter
    1.4.2在Service中使用分页:
            
            
              java
              
              
            
          
          @Override
public PageInfo getUsersByPage(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List users = userMapper.selectAll();
    return new PageInfo<>(users);
}2. 动态SQL
在XML中使用动态SQL:
            
            
              xml
              
              
            
          
              SELECT id, name, age, email 
    FROM user
    
        
            AND name LIKE CONCAT('%', #{name}, '%')
        
        
            AND age = #{age}
        
    3. 批量操作
批量插入用户:
            
            
              xml
              
              
            
          
              INSERT INTO user(name, age, email) VALUES
    
        (#{user.name}, #{user.age}, #{user.email})
    最佳实践
- 
使用Mapper接口注解:对于简单的CRUD操作,可以使用注解方式,代码更简洁。 
- 
复杂SQL使用XML:对于复杂的SQL语句,建议使用XML配置,便于维护和优化。 
- 
合理使用事务:在Service层使用@Transactional注解管理事务。 
- 
避免N+1查询问题:合理设计查询,避免循环查询数据库。 
- 
SQL优化:注意SQL语句的优化,添加合适的索引。 
- 
连接池配置:合理配置数据库连接池参数。 
总结
本文详细介绍了如何在Spring Boot项目中整合MyBatis进行数据访问操作。我们学习了:
- MyBatis的基本概念和优势
- 如何在Spring Boot中添加MyBatis依赖
- 数据库连接配置
- 实体类、Mapper接口和XML配置的创建
- Service层和Controller层的实现
- MyBatis的高级特性和最佳实践
通过整合Spring Boot和MyBatis,我们可以快速构建功能完善的Web应用,同时享受两者带来的便利。在下一篇文章中,我们将介绍如何构建RESTful API。
作者:CSDN博客助手
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。