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

MyBatis使用接口映射的方法步驟

 更新時間:2024年07月05日 09:47:00   作者:辭暮爾爾-煙火年年  
映射器是MyBatis中最核心的組件之一,本文主要介紹了MyBatis使用接口映射的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

在MyBatis中使用接口映射是一種基于Java接口而非XML映射文件的方式來綁定SQL查詢和操作。這種方法使用注解來指定SQL語句,并將其直接關聯到接口方法上。通過這種方式,可以省去編寫XML映射文件的工作,而且使得SQL語句和Java代碼的關系更直觀。

1. 定義一個Mapper接口

首先,定義一個接口來表示你的數據庫操作。例如,如果你有一個User表,你可以創(chuàng)建一個UserMapper接口:

public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(Integer id);
    
    @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUser(User user);
    
    @Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}")
    void updateUser(User user);
    
    @Delete("DELETE FROM users WHERE id=#{id}")
    void deleteUser(Integer id);
}

這個接口定義了基本的增刪改查操作,并通過注解@Select@Insert、@Update、@Delete與SQL語句相關聯。

2. 配置MyBatis使用注解

接下來,在MyBatis配置文件中指定你的接口。你無需指定XML文件,因為你用注解定義了SQL語句。

mybatis-config.xml 示例(無需mapper XML聲明)

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper class="org.example.mapper.UserMapper"/>
    </mappers>
</configuration>

3. 在代碼中使用Mapper接口

創(chuàng)建SqlSessionFactorySqlSession,然后通過SqlSession獲取Mapper接口的實例。

try (SqlSession session = sqlSessionFactory.openSession()) {
    UserMapper mapper = session.getMapper(UserMapper.class);
    
    // 使用mapper操作數據庫
    User user = mapper.getUserById(1);
    System.out.println(user.getName());
    
    // 更多的數據庫操作...
}

4. 深入源碼分析

在MyBatis初始化過程中,當你調用getMapper(Class<T> type)方法時,MyBatis內部使用了JDK動態(tài)代理來創(chuàng)建Mapper接口的實現。

public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
}

Configuration類中,getMapper方法會調用mapperRegistry中的getMapper方法,該方法最終調用了MapperProxyFactory來創(chuàng)建Mapper代理:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
        throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
        return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
        throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
}

MapperProxyFactory創(chuàng)建代理對象:

public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
}

protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
}

MapperProxy是實際的代理類,它實現了InvocationHandler接口。每當你調用一個Mapper接口的方法時,都會調用invoke方法。在這個方法中,MyBatis會判斷該調用是否對應一個SQL操作,并執(zhí)行相應的SQL語句:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
    } else {
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }
}

5. 細節(jié)和最佳實踐

  • 使用注解時,確保你的SQL語句不會過于復雜。對于復雜的SQL,考慮使用XML映射文件。
  • 明確區(qū)分@Param注解來綁定方法參數,尤其是在參數超過一個的方法中,這樣可以在SQL語句中更容易地引用參數。
  • 使用@Options注解來調整MyBatis的行為,例如獲取自動生成的鍵。
  • 保持Mapper接口的清晰和簡潔,邏輯復雜時考慮將其拆分。

通過以上步驟和解析,你可以在MyBatis中成功地使用接口映射,以簡潔和直觀的方式進行數據庫操作。

到此這篇關于MyBatis使用接口映射的方法步驟的文章就介紹到這了,更多相關MyBatis 接口映射內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java線程生命周期的終止與復位

    Java線程生命周期的終止與復位

    這篇文章主要介紹了Java線程生命周期的終止與復位,Java的線程狀態(tài)描述放在Thread類里面的枚舉類State中.總共包含了6中狀態(tài),具體詳情需要的小伙伴可以參考一下文章描述
    2022-07-07
  • Zuul 如何屏蔽服務和指定路徑

    Zuul 如何屏蔽服務和指定路徑

    這篇文章主要介紹了Zuul 如何屏蔽服務和指定路徑的實現方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • MyBatis輸入映射和輸出映射實例詳解

    MyBatis輸入映射和輸出映射實例詳解

    mapper.xml是我們配置操作數據庫的sql語句的地方.這篇文章主要介紹了MyBatis輸入映射和輸出映射實例詳解,需要的朋友可以參考下
    2017-02-02
  • 淺析Java Scanner 類的用法

    淺析Java Scanner 類的用法

    這篇文章主要介紹了Java Scanner 類的用法,文中講解非常詳細,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • MyBatis Mapper XML中比較操作符轉義問題解決

    MyBatis Mapper XML中比較操作符轉義問題解決

    在使用MyBatis編寫Mapper XML時,有時會遇到比較操作符需要進行轉義的情況,本文主要介紹了MyBatis Mapper XML中比較操作符轉義問題解決,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • SpringBoot整合mybatis結合pageHelper插件實現分頁

    SpringBoot整合mybatis結合pageHelper插件實現分頁

    在本篇文章里小編給大家整理的是關于SpringBoot整合mybatis使用pageHelper插件進行分頁操作相關知識點,需要的朋友們學習下。
    2020-02-02
  • 關于SpringBoot創(chuàng)建存儲令牌的媒介類和過濾器的問題

    關于SpringBoot創(chuàng)建存儲令牌的媒介類和過濾器的問題

    這篇文章主要介紹了SpringBoot創(chuàng)建存儲令牌的媒介類和過濾器的問題,需要在配置文件中,添加JWT需要的密匙,過期時間和緩存過期時間,具體實例代碼參考下本文
    2021-09-09
  • Java pdu短信解碼全面解析

    Java pdu短信解碼全面解析

    本文是根據python的方法改寫的pdu短信解碼,非常不錯,代碼簡單易懂具有參考借鑒價值,感興趣的朋友一起看看吧
    2016-10-10
  • JUnit4 Hamcrest匹配器常用方法總結

    JUnit4 Hamcrest匹配器常用方法總結

    這篇文章主要介紹了JUnit4 Hamcrest匹配器常用方法總結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-11-11
  • Spring?Cloud?Eureka?搭建?&?集群方式

    Spring?Cloud?Eureka?搭建?&?集群方式

    這篇文章主要介紹了Spring?Cloud?Eureka?搭建?&?集群方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03

最新評論