欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot集成MyBatis的多種方式

 更新時(shí)間:2023年12月19日 10:19:19   作者:IT·陳寒  
本文深入解析了Spring Boot集成MyBatis的多種方式,包括XML配置、注解配置以及MyBatis的動態(tài)SQL等,具有一定的參考價(jià)值,感興趣的可以了解一下

1. 引言

Spring Boot作為一款快速開發(fā)、簡化配置的框架,與MyBatis的結(jié)合使用是開發(fā)中常見的組合。本文將深入探討Spring Boot集成MyBatis的多種方式,包括XML配置、注解配置以及MyBatis的動態(tài)SQL等,通過實(shí)例代碼和詳細(xì)解釋,幫助讀者選擇適合自己項(xiàng)目的集成方式

2. 傳統(tǒng)的XML配置方式

2.1 引入依賴

首先,在pom.xml文件中添加MyBatis和數(shù)據(jù)庫驅(qū)動的依賴:

<dependencies>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!-- 數(shù)據(jù)庫驅(qū)動 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2.2 配置數(shù)據(jù)源和MyBatis

application.propertiesapplication.yml中配置數(shù)據(jù)源和MyBatis:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: sa
    password:
  h2:
    console:
      enabled: true
  mybatis:
    mapper-locations: classpath:/mapper/*.xml

在上述配置中,spring.datasource用于配置數(shù)據(jù)源,mybatis.mapper-locations指定了MyBatis的XML映射文件的位置。

2.3 編寫Mapper接口和XML映射文件

創(chuàng)建一個(gè)User實(shí)體類:

public class User {
    private Long id;
    private String username;
    private String password;
    // 省略getter和setter
}

創(chuàng)建一個(gè)UserMapper接口:

public interface UserMapper {
    User selectUserById(Long id);
    void insertUser(User user);
}

編寫UserMapper的XML映射文件UserMapper.xml

<!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="BaseResultMap" type="com.example.entity.User">
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
    </resultMap>

    <select id="selectUserById" resultMap="BaseResultMap">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <insert id="insertUser">
        INSERT INTO user (username, password) VALUES (#{username}, #{password})
    </insert>

</mapper>

2.4 使用Mapper

在Service或Controller中使用UserMapper:

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    public void createUser(User user) {
        userMapper.insertUser(user);
    }
}

這樣,通過XML配置方式,我們完成了Spring Boot與MyBatis的集成。

3. 注解配置方式

3.1 引入依賴

同樣,在pom.xml文件中添加MyBatis和數(shù)據(jù)庫驅(qū)動的依賴:

<dependencies>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!-- 數(shù)據(jù)庫驅(qū)動 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

3.2 配置數(shù)據(jù)源和MyBatis

application.propertiesapplication.yml中配置數(shù)據(jù)源和MyBatis:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: sa
    password:
  h2:
    console:
      enabled: true
  mybatis:
    mapper-locations: classpath:/mapper/*.xml

3.3 編寫Mapper接口

創(chuàng)建一個(gè)UserMapper接口,并使用注解配置SQL語句:

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectUserById(Long id);

    @Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})")
    void insertUser(User user);
}

3.4 使用Mapper

在Service或Controller中使用UserMapper:

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    public void createUser(User user) {
        userMapper.insertUser(user);
    }
}

通過注解配置方式,我們實(shí)現(xiàn)了Spring Boot與MyBatis的集成,使得Mapper接口的SQL語句更加直觀。

4. MyBatis動態(tài)SQL

4.1 使用XML配置方式

動態(tài)SQL是MyBatis的一個(gè)強(qiáng)大特性,可以根據(jù)不同條件拼接SQL語句,從而實(shí)現(xiàn)更加靈活的查詢。下面是一個(gè)簡單的例子,使用MyBatis的動態(tài)SQL:

<!-- UserMapper.xml -->

<mapper namespace="com.example.mapper.UserMapper">

    <select id="selectUsersByCondition" parameterType="java.util.Map" resultType="com.example.entity.User">
        SELECT * FROM user
        <where>
            <if test="username != null">
                AND username = #{username}
            </if>
            <if test="age != null">
                AND age = #{age}
            </if>
        </where>
    </select>

</mapper>

在上述代碼中,我們使用<where>標(biāo)簽包裹條件判斷,通過<if>標(biāo)簽判斷是否需要拼接對應(yīng)的條件語句。

4.2 使用注解配置方式

通過注解配置方式使用動態(tài)SQL:

// UserMapper.java

@Mapper
public interface UserMapper {

    @SelectProvider(type = UserSqlProvider.class, method = "selectUsersByCondition")
    List<User> selectUsersByCondition(Map<String, Object> condition);
}
// UserSqlProvider.java

public class UserSqlProvider {

    public String selectUsersByCondition(Map<String, Object> condition) {
        return new SQL() {{
            SELECT("*");
            FROM("user");
            if (condition.get("username") != null) {
                WHERE("username = #{username}");
            }
            if (condition.get("age") != null) {
                WHERE("age = #{age}");
            }
        }}.toString();
    }
}

在上述代碼中,通過@SelectProvider注解指定了使用的Provider類和方法,Provider類中動態(tài)生成SQL語句。

5. MyBatis的插件機(jī)制

MyBatis提供了插件機(jī)制,可以通過插件對SQL的執(zhí)行過程進(jìn)行干預(yù)和增強(qiáng)。以下是一個(gè)簡單的插件示例:

// MyPlugin.java

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MyPlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 在原方法執(zhí)行前進(jìn)行處理
        System.out.println("Before update...");

        // 調(diào)用原方法
        Object result = invocation.proceed();

        // 在原方法執(zhí)行后進(jìn)行處理
        System.out.println("After update...");

        return result;
    }

    @Override
    public Object plugin(Object target) {
        // 將插件應(yīng)用到Executor對象上
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 設(shè)置插件屬性
    }
}

在上述代碼中,通過@Intercepts@Signature注解指定了攔截的方法和參數(shù)類型,實(shí)現(xiàn)了Interceptor接口。在intercept方法中可以對原方法進(jìn)行干預(yù),plugin方法將插件應(yīng)用到目標(biāo)對象上。

6. 性能優(yōu)化與拓展

6.1 緩存機(jī)制

MyBatis提供了一級緩存和二級緩存兩種緩存機(jī)制。一級緩存是SqlSession級別的緩存,而二級緩存是Mapper級別的緩存。在需要優(yōu)化查詢性能時(shí),可以考慮使用MyBatis的緩存機(jī)制。

6.2 批量操作

MyBatis支持批量插入、更新和刪除操作,通過批量操作可以減少數(shù)據(jù)庫交互次數(shù),提高性能。

6.3 多數(shù)據(jù)源配置

在實(shí)際項(xiàng)目中,可能會遇到需要連接多個(gè)數(shù)據(jù)源的情況。Spring Boot和MyBatis提供了多數(shù)據(jù)源的支持,可以通過配置多個(gè)DataSourceSqlSessionFactory來實(shí)現(xiàn)。

7. 總結(jié)

本文深入解析了Spring Boot集成MyBatis的多種方式,包括XML配置、注解配置以及MyBatis的動態(tài)SQL等。通過實(shí)例代碼和詳細(xì)解釋,讀者能夠更好地理解這些集成方式的使用場景和優(yōu)劣。同時(shí),了解了MyBatis的插件機(jī)制、緩存機(jī)制以及一些性能優(yōu)化的方法。在實(shí)際項(xiàng)目中,根據(jù)具體需求選擇合適的集成方式和優(yōu)化策略,能夠更好地發(fā)揮Spring Boot和MyBatis的優(yōu)勢,提升開發(fā)效率和系統(tǒng)性能。

到此這篇關(guān)于SpringBoot集成MyBatis的多種方式的文章就介紹到這了,更多相關(guān)SpringBoot集成MyBatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot如何讀取sftp的文件

    springboot如何讀取sftp的文件

    這篇文章主要介紹了springboot如何讀取sftp的文件,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java面試常見問題---ConcurrentHashMap

    java面試常見問題---ConcurrentHashMap

    ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識,一起看看吧
    2021-06-06
  • Java通過反射機(jī)制將對象封裝成JSON和JsonArray格式

    Java通過反射機(jī)制將對象封裝成JSON和JsonArray格式

    這篇文章主要介紹了Java通過反射機(jī)制將對象封裝成JSON和JsonArray格式,JAVA反射機(jī)制是在運(yùn)行狀態(tài)中,對于任意一個(gè)實(shí)體類,都能夠知道這個(gè)類的所有屬性和方法,需要的朋友可以參考下
    2023-10-10
  • IDEA?maven項(xiàng)目依賴無法解析問題

    IDEA?maven項(xiàng)目依賴無法解析問題

    這篇文章主要介紹了IDEA?maven項(xiàng)目依賴無法解析問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • java實(shí)現(xiàn)簡單掃雷游戲

    java實(shí)現(xiàn)簡單掃雷游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡單掃雷游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • Java如何通過反射獲取Constructor、Field、Method對象

    Java如何通過反射獲取Constructor、Field、Method對象

    反射指的是對象的反向處理操作,根據(jù)對象取得對象的來源信息,在反射的世界里面,看重的不再是一個(gè)對象,而是對象身后的組成,下面這篇文章主要給大家介紹了關(guān)于Java如何通過反射獲取Constructor、Field、Method對象的相關(guān)資料,需要的朋友可以參考下
    2022-06-06
  • Sentinel 整合SpringCloud的詳細(xì)教程

    Sentinel 整合SpringCloud的詳細(xì)教程

    Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服務(wù)一站式解決方案,這篇文章主要介紹了Sentinel 之 整合SpringCloud的相關(guān)知識,需要的朋友可以參考下
    2021-10-10
  • 關(guān)于servlet向mysql添加數(shù)據(jù)時(shí)中文亂碼問題的解決

    關(guān)于servlet向mysql添加數(shù)據(jù)時(shí)中文亂碼問題的解決

    最近在工作中遇到一個(gè)小問題,出現(xiàn)了中文亂碼的問題,無奈只能想辦法解決,下面這篇文章主要給大家介紹了關(guān)于servlet向mysql添加數(shù)據(jù)時(shí)中文亂碼問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-08-08
  • 在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法

    在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法

    這篇文章主要介紹了在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法,一定程度上有助于提高安卓程序的使用體驗(yàn),需要的朋友可以參考下
    2015-07-07
  • Slf4j+logback實(shí)現(xiàn)JSON格式日志輸出方式

    Slf4j+logback實(shí)現(xiàn)JSON格式日志輸出方式

    這篇文章主要介紹了Slf4j+logback實(shí)現(xiàn)JSON格式日志輸出方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12

最新評論