몬그로이

MyBatis 본문

Organizing Docs/Java Docs

MyBatis

Mon Groy 2024. 6. 27. 20:00

 

Processing to run once : application 실행 시 처음에 한 번 작동하는 프로세스

(1) : application 이 SqlSession Factory Builder를 build 하도록 요청

(2) ~ (3) : SqlSession Factory Builder 가 설정된 MyBatis Config File 을 참고하여 SqlSession Factory 를 생성함

 

Processing to run per requests : application 이 작동하는 동안 수행되는 프로세스

(4) : client 로부터 request 를 받음

(5) : application 이 SqlSession Factory 에게 SqlSession 을 생성하도록 시킴

(6) : 그에 따라 config 설정에 맞게 SqlSession 를 생성함

(7) ~ (8) : application 이 SqlSession 을 확인하여 Mapper Interface 를 호출

(9) ~ (10) : SqlSession 이 Mapper Interface 를 기반으로, Mapping File 에서 실행할 매핑 SQL을 가져와 실행함


MyBatis Config File

(2)에 해당

<!-- /resources/mybatis-config.xml -->

<!DOCTYPE configuration

        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

         "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

         <typeAliases>

                  <package name="com.thesun4sky.querymapper.domain"/>

         </typeAliases>

         <mappers>

                  <mapper resource="mapper/UserMapper.xml"/>

         </mappers>

</configuration>

 

패키지 경로: 매핑해줄 객체가 들어있음

Mapping File 목록을 지정해주는 설정 파일 포함


Mapper Interface 를 사용하여 매핑하는 방법

(8) ~ (9) 에 해당

 

1. Dao 클래스 정의 :

SqlSession 을 직접적으로 사용하는 방법

SqlSession 멤버 변수로 사용하며 쿼리파일 수행 요청

@Component

public class UserDao {

 

     // SqlSession 멤버 변수로 사용하며 쿼리파일 수행 요청

      private final SqlSession sqlSession;

 

     public UserDao(SqlSession sqlSession) {

      this.sqlSession = sqlSession;

      }

 

      public User selectUserById(long id) {

      return this.sqlSession.selectOne("selectUserById", id); //selectOne 메서드를 직접 호출

      } //첫번째 문자열 인자로 쿼리ID( selectUserById)를 넣는다 -> Mapping File 에 정의된 쿼리문 실행 됨

 

 }

 

 

2. Mapper Interface 정의:
SqlSession 를 간접적으로 사용하는 방법

@Mapper

public interface UserMapper { //클래스가 아니라 interface임

 

      User selectUserById(@Param("id") Long id);

 

}

org.apache.ibatis.annotation.Mapper 어노테이션(ibatis에서 구현)을 사용하면

sqlSession을 사용하여 자동 호출해 줌

xml 파일(Mapping File) 에 정의되어있는 이름과 같은 이름의 메서드 명을 사용하면 됨

( 쿼리문 id와 mapper 메소드 명 일치시키기)

그러면 xml 파일에 정의된 id 값과 매칭이 됨

 

* 이 때, User 객체는 implements Serializable 이 되어있어야 객체를 만들어 값을 넣을 수 있음

public class User implements Serializable {

    // 생략

}

 

application (클래스) 내에서 다음과 같이 호출 가능 - Dao 를 사용하는 경우와 Mapper 를 사용하는 경우

// 어플리케이션 실행 컨텍스트 생성

var context = SpringApplication.run(QueryMappingApplication.class, args);

 

// 데이터 조회 DAO 클래스 조회

var dao = context.getBean(UserDao.class);

// DAO 통해 유저정보 조회

System.out.println("User by dao : " + dao.selectUserById(1L)); // data.sql 에서 미리 저장된것이 하나 있어서 2

 

// 데이터 조회 Mapper 클래스 조회

var mapper = context.getBean(UserMapper.class);

// FileMapper 통해 유저정보 조회

System.out.println("User by fileMapper: " + mapper.selectUserById(1L));

 


Mapping File

(10) 에 해당

 

SqlSession 가 실행하는 쿼리가 담긴 파일로

쿼리 수행결과를 어떤 인터페이스 매핑할지 정의해놓은 파일

<!-- UserMapper.xml -->

<!DOCTYPE mapper

          PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

          "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.thesun4sky.querymapper.mapper.UserMapper"> // UserMapper 에 매핑한다는 뜻

          <select id="selectUserById" resultType="User"> // UserMapper 에서 사용하는 메서드명, 반환타입과 일치

                    select id, name from users where id = #{id}

          </select>

</mapper>

 


조회할 데이터 미리 만들어 두어야 조회가능:

resources 디렉토리 하위에 만든다

//data.sql 파일 (apoplication 이 실행될 때 작동)

 

insert into users (name) values ('Kim'); //insert 이므로 user 생성해 줌

 

 

//schema.sql 파일 (기존 테이블 날리고 생성해 줌)

 

drop table if exists users;

 

create table users (id int primary key auto_increment, name varchar);

 


H2 에서 작동시키기 위한 설정 파일로 resources 디렉토리 하위에 둔다

//application.yml 파일

 

spring:

     application.name: query-mapper

     # H2 Database ??

     datasource:

         driver-class-name: org.h2.Driver

        url: 'jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE' # H2 DB ?? ?? (In-Memory Mode)

          #url: 'jdbc:h2:~/test' # H2 DB ?? ?? (Embedded Mode)

          username: sa # H2 DB ?? ID (??? ??)

          password: # H2 DB ?? PW (??? ??)

    

     # H2 Console ??

     h2:

          console: # H2 DB? ??? ??? ? ?? ??

               enabled: true # H2 Console ?? ??

              path: /h2-console # H2 Console ?? ??

 

      mybatis.config-location: classpath:mybatis-config.xml

 


application 실행 클래스

  @SpringBootApplication

   public class QueryMappingApplication {

            public static void main(String[] args) {

                           // 어플리케이션 실행 컨텍스트 생성

                           var context = SpringApplication.run(QueryMappingApplication.class, args);

  

                            // 데이터 조회 DAO 클래스 조회

                            var dao = context.getBean(UserDao.class);

                            // DAO 통해 유저정보 조회

                            System.out.println("User by dao : " + dao.selectUserById(1L));

        

                            // 데이터 조회 Mapper 클래스 조회

                           var mapper = context.getBean(UserMapper.class);

                            // FileMapper 통해 유저정보 조회

                            System.out.println("User by fileMapper: " + mapper.selectUserById(1L)); 

             }

}

 

'Organizing Docs > Java Docs' 카테고리의 다른 글

Spring Data JPA  (0) 2024.06.28
페이징  (0) 2024.06.28
데이터베이스Driver >> JDBCTemplate  (0) 2024.06.26
자바의 정석 6. 객체지향 프로그래밍1  (1) 2024.06.19
자바의 정석 5. 배열(Array)  (0) 2024.06.18