스프링 db2 - MyBatis

2023. 2. 1. 21:09spring/db

2/1

 

* 설정

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'

2.2.0 -> 버전정보 별도로 추가해야 된다.

 

applicatoin properties 설정 예시

#MyBatis
mybatis.type-aliases-package=hello.itemservice.domain
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.hello.itemservice.repository.mybatis=trace

 

  • type-aliases-pakage: 패키지명 생략 
  • configuration.map-underscore-to-camel-case : 언더바 문법을 카멜 문법으로 자동 변경해준다.

 

* Mapper 클래스 생성 

@Mapper
public interface ItemMapper {

    void save(Item item);

    //파라미터가 두 개 이상이 넘어가는 경우에는 @Param을 붙여야 된다.
    void update(@Param("id") Long id, @Param("updateParam") ItemUpdateDto updateParam);

    List<Item> findAll(ItemSearchCond itemSearch);

    Optional<Item> findById(Long id);
}

- @Mapper 등록해야 스프링 컨테이너가 MyBatis 에 사용될 Mapper임을 인지하고 빈에 생성한다.

- 해당 클래스는 java 폴더 내부에 있지만 실제 MyBatis가 사용될 .xml 파일은 resource 내부에 있어야 한다.

- 경로가 일치해야 한다.

 

 

<mapper namespace="hello.itemservice.repository.mybatis.ItemMapper">

<mapper namespace = 경로/경로/경로/경로/맵퍼

 


* 기본 문법 -> #{ 파라미터명} 

<insert id ="save" useGeneratedKeys="true" keyProperty="id">
    insert into item (item_name, price, quantity)
    values (#={itemName}, #={price}, #={quantity})
</insert>

*useGeneratedKey -> Auto Crement

*KeyProperty -> PK

<update id="update">
    update item
    set item_name=#={updateParam.itemName},
        price=#={updateParam.price},
        quantity=#={updateParam.quantity}
    where id = #={id}
</update>
<select id="findById" resultType="Item">
    select id, item_name, price, quantity
    from item
    where id = # ={id};
</select>

* resultType -> select 시 반환 받을 타입 설정

- 원래는 경로명 전부 작성해야 하지만 설정해놓았기 때문에 하위 폴더만 작성하면 된다.

mybatis.type-aliases-package=hello.itemservice.domain

 


*동적 쿼리

if

choose,when, otherwise

trim,where, set

foreach

<select id="findAll" resultType="Item">
    select id, item_name, price, quantity
    from item
    <where>
        <if test="itemName != null and itemName != ''">
            and item_name = like concat('%',#={itemName},'%')
        </if>

        <if test="maxPrice !=null">
            and price $lt;= #={maxPrice};
        </if>
    </where>
</select>

 

<if>  : 조건이 참일 경우에만 실행(생성)되도록 한다. 주로 <where> 과 묶어서 사용한다.

<choose, when, otherwise> 

: <choolse> 내부에서 <when> , <otherwise> 를 사용하는데

when -> 자바의 swich문

otehrwise -> 자바의 else 와 같이 사용한다.

 


* 참고 - XML 파일 경로 수정하기

> XML 파일을 원하는 위치에 두고 싶으면 application.properties 에 다음과 같이 설정하면 된다.

> mybatis.mapper-locations=classpath:mapper/**/*.xml 

> 이렇게 하면 resources/mapper 를 포함한 그 하위 폴더에 있는 XML을 XML 매핑 파일로 인식한다. 이 경우 파일 이름은 자유롭게 설정해도 된다. 

> 참고로 테스트의 application.properties 파일도 함께 수정해야 테스트를 실행할 때 인식할 수 있다

 

 

 

* Mapper 인터페이스가 구현체 없이 사용되는 동작 원리 (동적 프록시 기술)