Kotlin Spring + Mybatis + Mysql 샘플 데이터 토이프로젝트 -5 Mybatis xml 설정

선종우·2024년 6월 3일
0

Spring 노트

목록 보기
5/10
  • Spring에 mybatis를 xml 기반으로 적용하는 내용이다.

  • mybatis api문서에서는 기본 프로젝트 구조를 아래와 같이 소개한다.
/my_application
  /bin
  /devlib
  /lib                <-- MyBatis *.jar files go here.
  /src
    /org/myapp/
      /action
      /data           <-- MyBatis artifacts go here, including, Mapper Classes, XML Configuration, XML Mapping Files.
        /mybatis-config.xml
        /BlogMapper.java
        /BlogMapper.xml
      /model
      /service
      /view
    /properties       <-- Properties included in your XML Configuration go here.
  /test
    /org/myapp/
      /action
      /data
      /model
      /service
      /view
    /properties
  /web
    /WEB-INF
      /web.xml

그러나 기본 intellij + gradle 환경에서는 위와 같이 xml파일을 java 파일과 같이 위치시키면 안 된다.(jar 파일로 압축되는 과정에서 .java, .kts 등의 확장자 외 파일은 제외된다.)


  • Spring boot + intellij + gradle을 사용하고 있는 경우 아래와 같이 xml을 이용해 프로젝트를 진행한다.

  • xml등과 같은 파일은 resources 경로에 위치시킨다. 경로를 변경시키고 싶은 경우에는 yaml파일에 설정을 변경해 주면 된다.

/src
	/main
    	/kotlin
        /resources
        	/mapper
            	employeeMapper.xml

  • application.yaml
mybatis:
  mapper-locations: classpath:mapper/*.xml
  • xml과 대응시키는 Mapper 인터페이스는 java, kotlin 폴더에 생성한다
@Mapper
interface EmployeeXmlMapper {
    fun findByFirstName(firstName: String): Employee?
}
  • 이에 대응하는 xml 파일은 아래와 같이 작성한다
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.repository.mapper.EmployeeXmlMapper">
    <select id="findByFirstName" resultType="com.example.domain.Employee">
        select * from employees where first_name = #{firstName}
    </select>
</mapper>

0개의 댓글