자니노트

[MyBatis] Cache(캐시) 관련 문제 - flushCache, useCache 본문

자바

[MyBatis] Cache(캐시) 관련 문제 - flushCache, useCache

zaninote 2023. 3. 3. 17:25

목차

    1. 개요

    MyBatis의 캐시는 Local Session Cache와 Second Level Cache 두가지로 구성되어 있다.

    간단히 정의하면 Local Sesion Cache 무조건적으로 활성화 되며 SqlSession 객체에 Cache가 되며 Second Level Cache는 Mapper namespace 단위로 Cache가 되며 On/Off 설정이 가능하다.

    MyBatis Cache 구조

    1-1. Local Session Cache

    새 세션이 생성될 때마다 MyBatis는 로컬 캐시를 생성하여 세션에 연결합니다.세션 내에서 실행된 쿼리는 로컬캐시에 저장되므로 동일한 입력 파라미터를 사용하여 동일한 쿼리를 더 이상 실행해도 데이터베이스에 영향을 주지 않습니다.

    기본적으로는 전체 세션 기간 동안 로컬 캐시 데이터가 사용되며 Local Cache는 commit or rollback, insert, update, delete close시에 clear 됩니다.

     

    이 캐시는 순환 참조를 해결하고 반복된 중첩된 쿼리 속도를 높이기 위해 필요합니다.따라서 완전히 비활성화할 수는 없지만 로컬 캐시가 스테이트먼트 실행 기간 동안만 사용하도록 설정할 수 있습니다.

    // clearCache를 호출하여 캐시를 지울 수 있음
    void clearCache()

    정리하면

    • 같은 쿼리 호출시 캐시에서 가져온다.
    • 적용범위는 default 값이 SESSION 이다.

    1-2. Second Level Cache

    •   mapper namespace 단위로 적용
    • Second level cache는 끄고 켤 수 있다.

    2. 사용 방법

    MyBatis 캐시를 설정하는 방법은 다음과 같습니다:

    2-1. MyBatis 구성 파일에서 캐싱을 활성화합니다:

    <configuration>
        <settings>
            <setting name="cacheEnabled" value="true"/>
        </settings>
        ...
    </configuration>

    2-2. 사용할 캐싱 메커니즘을 구성합니다:

    MyBatis는 LRU, FIFO 및 SoftCache와 같은 여러 캐싱 메커니즘을 제공합니다. MyBatis 구성 파일의 <cache> 요소에서 type 속성을 설정하여 캐싱 메커니즘을 구성할 수 있습니다. LRU 캐시를 사용하는 예는 다음과 같습니다:

    <configuration>
        <settings>
            <setting name="cacheEnabled" value="true"/>
        </settings>
        <cache type="org.apache.ibatis.cache.decorators.LruCache">
            <property name="size" value="1024"/>
        </cache>
        ...
    </configuration>

    2-3. 특정 문에 대한 캐싱을 구성합니다:

    mapper 파일의 statement 요소에 useCache 속성을 추가하여 특정 문에 대한 캐싱을 구성할 수 있습니다. 다음은 사용자를 선택하는 예입니다:

    <mapper namespace="com.example.MyMapper">
        <select id="selectUser" resultType="User" useCache="true">
            select * from user where id = #{id}
        </select>
    </mapper>

    이 예에서 selectUser 문은 캐시됩니다.

    2-4. 특정 결과 집합에 대한 캐싱을 구성합니다:

    mapper 파일의 statement 요소에 resultCache 속성을 추가하여 특정 결과 집합에 대한 캐싱을 구성할 수 있습니다. 다음은 사용자 캐시를 사용하는 예입니다:

    <mapper namespace="com.example.MyMapper">
        <select id="selectUser" resultType="User" resultCache="userCache">
            select * from user where id = #{id}
        </select>
    </mapper>

    이 예에서 selectUser 문은 userCache라는 이름의 캐시를 사용합니다.

    2-5. 특정 매개 변수 값에 대한 캐싱을 구성합니다:

    flushCache="true" 속성을 사용하여 특정 매개 변수 값에 대한 캐싱을 구성할 수 있습니다. 다음은 사용자를 선택하는 예입니다:

    <mapper namespace="com.example.MyMapper">
        <select id="selectUser" resultType="User" flushCache="true">
            select * from user where id = #{id}
        </select>
    </mapper>

    이 예에서는 selectUser 문이 다른 매개 변수 값으로 실행될 때마다 캐시가 플러시됩니다.

    이것으로 MyBatis에서 캐싱을 설정하여 데이터베이스 쿼리의 성능을 향상시킬 수 있습니다.

     


    참조

    https://umbum.dev/1201

     

    [MyBatis] Cache

    간단히 정리하면, MyBatis는 2가지 캐시를 제공한다. local session cache, second level cache second level cache https://idea-sketch.tistory.com/31 mapper namespace 단위로 적용. `` `` 구문. 캐시 설정 파라미터 : 캐시 size, evic

    umbum.dev

    https://idea-sketch.tistory.com/31

     

    [MyBatis] MyBatis 캐시에 대해 알아보기(2)

    지난번 포스팅(http://idea-sketch.tistory.com/30)에 이어서 이번에는 Second level cache 이다. - Second level cache - Second level cache 는 Local cache 와는 다르게 끄고 킬 수 있다. cache를 키는 방법은 Config 설정하는 곳

    idea-sketch.tistory.com

    https://idea-sketch.tistory.com/30

     

    [MyBatis] MyBatis 캐시에 대해 알아보기(1)

    아주 오~~~랜만에 포스팅이다. 1년전 이맘때쯤 써야지 했던 내용인데 귀차니즘 신이 와서 묵혀두었다가 이제야 쓰게되었다.하도 오랜만이라 내용을 많이 까먹었기에 오늘은 포스팅 내용중 반만

    idea-sketch.tistory.com

     

    '자바' 카테고리의 다른 글

    [Spring] @Primary Annotation 사용법  (0) 2023.03.13
    HikariCP 란?  (0) 2023.03.03
    Comments