Spring Boot 整合 MyBatis 连接数据库及常见问题

2025-03-27 14:50

本文主要是介绍Spring Boot 整合 MyBatis 连接数据库及常见问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot整合MyBatis连接数据库及常见问题》MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,下面详细介绍如何在SpringBoot项目中整合My...

MyBATis 是一个优秀的持久层框架,支持定制化 SQL、存储过程以及高级映射。下面详细介绍如何在 Spring Boot 项目中整合 MyBatis 并连接数据库。

一、基本配置

1. 添加依赖

pom.xml中添加以下依赖:

<!-- Spring Boot Starter Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Spring Boot Starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version> <!-- 使用最新版本 -->
</dependency>
<!-- 数据库驱动,根据你的数据库选择 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-Java</artifactId>javascript;
    <scope>runtime</scope>
</dependency>
<!-- 其他可能需要的依赖 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version> <!-- Druid 连接池 -->
</dependency>

2. 配置数据库连接

application.ymlapplication.properties中配置数据库连接:

# application.yml 配置示例
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
    username: your_username
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 使用Druid连接池
# MyBatis 配置
mybatis:
  mapper-locations: classpath:mapper/*.xml  # mapper.xml文件位置
  type-aliases-package: com.example.model   # 实体类所在包
  configuration:
    map-underscore-to-camel-case: true      # 开启驼峰命名转换

二、项目结构

典型的项目结构如下:

src/main/java
└── com.example.demo
    ├── DemoApplication.java          # 启动类
    ├── config
    │   └── MyBatisConfig.java        # MyBatis配置类(可选)
    ├── controller
    │   └── UserController.java       # 控制器
    ├── service
    │   ├── UserService.java          # 服务接口
    │   └── impl
    │       └── UserServiceImpl.java  # 服务实现
    ├── mapper
    │   └── UserMapper.java           # Mapper接口
    └── model
        └── User.java                 # 实体类
src/main/resources
├── application.yml                   # 配置文件
└── mapper
    └── UserMapper.xml                # SQL映射文件

三、核心组件实现(示例)

1. 实体类

package com.example.model;
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    // getters and setters
    // toString()
}

2. Mapper 接口

package com.example.mapper;
import com.example.model.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper // 重要:标识这是一个MyBatis的Mapper接口
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(Long id);
    @Insert("INSERT INTO user(username, password, email) VALUES(#{username}, #{password}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);
    @Update("UPDATE user SET username=#{username}, password=#{password}, email=#{email} WHERE id=#{id}")
    int update(User user);
    @Delete("DELETE FROM user WHERE id=#{id}")
    int delete(Long id);
    // XML配置方式
    List<User> findAll();
}

3. Mapper XML 文件

src/main/resources/mapper/UserMapper.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.example.mapper.UserMapper">
    <resultMap id="userResultMap" type="User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="email" column="email"/>
    </resultMap>
    <select id="findAll" resultMap="userResultMap">
        SELECT * FROM user
    </select>
</mapper>

4. Service 层


package com.example.service;
import com.example.model.Usjser;
import java.util.List;
public interface UserService {
    User findById(Long id)android;
    List<User> findAll();
    int save(User user);
    int update(User user);
    int delete(Long id);
}

service层实现类:

package com.example.service.impl;
import com.example.mapper.UserMapper;
import com.example.model.User;
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 findById(Long id) {
        return userMapper.findById(id);
    }
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
    @Override
    public int save(User user) {
        return userMapper.insert(user);
    }
    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
    @Override
    public int delete(Long id) {
        return userMapper.delete(id);
    }
}

5. Controller 层:

package com.example.controller;
import com.example.model.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;
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }
    @PostMapping
    public int createUser(@RequestBody User user) {
        return userService.save(user);
    }
    @PutMapping
    public int updateUser(@RequestBody User user) {
        return userService.update(user);
    }
    @DeleteMapping("/{id}")
    public int deleteUser(@PathVariable Long id) {
        return userService.delete(id);
    }
}

四、高级特性

1. 动态SQL

在XML中使用动态SQL:

<select id="findByCondition" parameterType="map" resultMap="userResultMap">
    SELECT * FROM user
    <where>
        <if test="username != null and username != ''">
            AND username LIKE CONCAT('%', #{username}, '%')
        </if>
        <if test="email != null and email != ''">
            AND email = #{email}
        </if>
    </where>
</select>

2. 分页查询

使用PageHelper插件:

添加依赖:

<select id="findByCondition" parameterType="map" resultMap="userResultMap">
    SELECT * FROM user
    <where>
        <if test="username != null and username != ''">
            AND username LIKE CONCAT('%', #{username}, '%')
        </if>
        <if test="email != null and email != ''">
            AND email = #{email}
        </if>
    </where>
</select>

使用示例:

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.1</version>
</dependency>

3. 多数据源配置

配置多个数据源:

spring:
  datasource:
    primary:
      url: jdbc:mysql://localhost:3306/db1
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
    secondary:
      url: jdbc:mysql://localhost:3306/DB2
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

创建配置类:

@Configuration
@MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperlocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));
        return bean.getObject();
    }
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
// 类似地创建SecondaryDataSourceConfig

五、常www.chinasem.cn见问题解决

Mapper接口无法注入

  • 确保启动类上有@MapperScan("com.example.mapper")注解
  • 或者每个Mapper接口上有@Mapper注解

XML文件找不到

  • 检查mybatis.mapper-locations配置是否正确
  • 确保XML文件在resources目录下正确位置

驼峰命名不生效

  • 确认配置mybatis.configuration.map-underscore-to-camel-case=true

连接池配置

  • 推荐使用Druid连接池,并配置合理的连接参数

事务管理

  • 在Service方法上添加@Transactional注解

到此这篇关于Spring Boot 整合 MyBatis 连接数据库及常见问题的文章就介绍到这了,更多相关Spring Boot MyBatis 连接数据库内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Spring Boot 整合 MyBatis 连接数据库及常见问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153969

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

MyBatis模糊查询报错:ParserException: not supported.pos 问题解决

《MyBatis模糊查询报错:ParserException:notsupported.pos问题解决》本文主要介绍了MyBatis模糊查询报错:ParserException:notsuppo... 目录问题描述问题根源错误SQL解析逻辑深层原因分析三种解决方案方案一:使用CONCAT函数(推荐)方案二:

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多