最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題

 更新時間:2025年03月27日 11:35:17   作者:上官簫羽  
MyBatis 是一個優(yōu)秀的持久層框架,支持定制化 SQL、存儲過程以及高級映射,下面詳細介紹如何在 Spring Boot 項目中整合 MyBatis 并連接數(shù)據(jù)庫,感興趣的朋友一起看看吧

MyBatis 是一個優(yōu)秀的持久層框架,支持定制化 SQL、存儲過程以及高級映射。下面詳細介紹如何在 Spring Boot 項目中整合 MyBatis 并連接數(shù)據(jù)庫。

一、基本配置

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>
<!-- 數(shù)據(jù)庫驅(qū)動,根據(jù)你的數(shù)據(jù)庫選擇 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- 其他可能需要的依賴 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version> <!-- Druid 連接池 -->
</dependency>

2. 配置數(shù)據(jù)庫連接

application.ymlapplication.properties中配置數(shù)據(jù)庫連接:

# 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      # 開啟駝峰命名轉(zhuǎn)換

二、項目結(jié)構(gòu)

典型的項目結(jié)構(gòu)如下:

src/main/java
└── com.example.demo
    ├── DemoApplication.java          # 啟動類
    ├── config
    │   └── MyBatisConfig.java        # MyBatis配置類(可選)
    ├── controller
    │   └── UserController.java       # 控制器
    ├── service
    │   ├── UserService.java          # 服務接口
    │   └── impl
    │       └── UserServiceImpl.java  # 服務實現(xiàn)
    ├── mapper
    │   └── UserMapper.java           # Mapper接口
    └── model
        └── User.java                 # 實體類
src/main/resources
├── application.yml                   # 配置文件
└── mapper
    └── UserMapper.xml                # SQL映射文件

三、核心組件實現(xiàn)(示例)

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.User;
import java.util.List;
public interface UserService {
    User findById(Long id);
    List<User> findAll();
    int save(User user);
    int update(User user);
    int delete(Long id);
}

service層實現(xiàn)類:

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. 動態(tài)SQL

在XML中使用動態(tài)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. 多數(shù)據(jù)源配置

配置多個數(shù)據(jù)源:

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

創(chuàng)建配置類:

@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);
    }
}
// 類似地創(chuàng)建SecondaryDataSourceConfig

五、常見問題解決

Mapper接口無法注入

  • 確保啟動類上有@MapperScan("com.example.mapper")注解
  • 或者每個Mapper接口上有@Mapper注解

XML文件找不到

  • 檢查mybatis.mapper-locations配置是否正確
  • 確保XML文件在resources目錄下正確位置

駝峰命名不生效

  • 確認配置mybatis.configuration.map-underscore-to-camel-case=true

連接池配置

  • 推薦使用Druid連接池,并配置合理的連接參數(shù)

事務管理

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

到此這篇關(guān)于Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題的文章就介紹到這了,更多相關(guān)Spring Boot MyBatis 連接數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot創(chuàng)建自定義Starter代碼實例

    SpringBoot創(chuàng)建自定義Starter代碼實例

    這篇文章主要介紹了SpringBoot創(chuàng)建自定義Starter代碼實例,自定義 Starter 是一種在軟件開發(fā)中常用的技術(shù),它可以幫助開發(fā)者快速搭建項目的基礎框架和配置,可以將一些常用的功能、依賴和配置封裝成一個可復用的模塊,方便在不同的項目中使用,需要的朋友可以參考下
    2023-11-11
  • Java中如何使用Gson將對象轉(zhuǎn)換為JSON字符串

    Java中如何使用Gson將對象轉(zhuǎn)換為JSON字符串

    這篇文章主要給大家介紹了關(guān)于Java中如何使用Gson將對象轉(zhuǎn)換為JSON字符串的相關(guān)資料,Gson是Google的一個開源項目,可以將Java對象轉(zhuǎn)換成JSON,也可能將JSON轉(zhuǎn)換成Java對象,需要的朋友可以參考下
    2023-11-11
  • 教你用java實現(xiàn)學生成績管理系統(tǒng)(附詳細代碼)

    教你用java實現(xiàn)學生成績管理系統(tǒng)(附詳細代碼)

    教學管理系統(tǒng)很適合初學者對于所學語言的練習,下面這篇文章主要給大家介紹了關(guān)于如何用java實現(xiàn)學生成績管理系統(tǒng)的相關(guān)資料,文中給出了詳細的實例代碼,需要的朋友可以參考下
    2023-06-06
  • SpringBoot LogbackvsLog4j2配置與性能測試對比分析

    SpringBoot LogbackvsLog4j2配置與性能測試對比分析

    本文主要對比了SpringBoot中Logback和Log4j2的日志框架,Logback作為Log4j的繼任者,性能穩(wěn)定,適合大多數(shù)應用場景,而Log4j2通過異步日志記錄方式,在高并發(fā)場景下性能優(yōu)越,支持多種配置方式,但配置相對復雜,需要排除默認的Logback依賴
    2025-12-12
  • springboot手動事務回滾的實現(xiàn)代碼

    springboot手動事務回滾的實現(xiàn)代碼

    這篇文章主要介紹了springboot手動事務回滾的實現(xiàn)方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • Java中Integer和int的使用及注意點

    Java中Integer和int的使用及注意點

    文章主要介紹了Java中Integer和Long類的緩存機制以及它們的比較方式,Integer和Long類在-128到127之間的值會被緩存,因此在這個范圍內(nèi)的值比較時可以使用==運算符,而超出這個范圍的值則需要使用equals()方法進行比較
    2025-01-01
  • java  Super 用法詳解及實例代碼

    java Super 用法詳解及實例代碼

    這篇文章主要介紹了java Super 用法詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • Java中的TreeSet集合詳解

    Java中的TreeSet集合詳解

    這篇文章主要介紹了Java中的TreeSet集合詳解,TreeSet 是一個 有序集合,它擴展了 AbstractSet 類并實現(xiàn)了 NavigableSet 接口,作為自平衡二叉搜索樹,二叉樹的每個節(jié)點包括一個額外的位,用于識別紅色或黑色的節(jié)點的顏色,需要的朋友可以參考下
    2023-09-09
  • Java多線程下載文件實現(xiàn)案例詳解

    Java多線程下載文件實現(xiàn)案例詳解

    這篇文章主要介紹了Java多線程下載文件實現(xiàn)案例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • 10分鐘帶你理解Java中的弱引用

    10分鐘帶你理解Java中的弱引用

    這篇文章將帶大家快速理解Java中弱引用,文章介紹的很詳細,對大家學習Java很有幫助哦,有需要的可以參考借鑒。
    2016-08-08

最新評論

鲁甸县| 临沧市| 江华| 榆林市| 宁乡县| 崇义县| 鹤峰县| 大港区| 冀州市| 宽城| 双柏县| 平顶山市| 洪泽县| 会宁县| 东兰县| 芮城县| 蒙城县| 沅江市| 资中县| 太原市| 砀山县| 巴塘县| 锦屏县| 北安市| 马关县| 习水县| 炉霍县| 宁安市| 丁青县| 资中县| 鹿邑县| 南宁市| 金湖县| 辛集市| 东明县| 濮阳市| 九台市| 宝清县| 漾濞| 三门峡市| 牟定县|