Skip to content

MyBATIS #

Find similar titles

1회 업데이트 됨.

Edit
  • 최초 작성자
    htBae
  • 최근 업데이트
    htBae

Structured data

Category
Database

MyBatis #

MyBatis는 자바 퍼시스턴스 프레임워크의 하나로 XML 서술자나 annotation을 사용하여 저장 프로시저나 SQL 문으로 객체들을 연결한다. MyBatis는 아파치 라이선스 2.0으로 배포되는 자유 소프트웨어이며 iBATIS 3.0의 포크로 iBATIS의 원 개발자들이 포함된 팀에 의해 유지 보수되고 있다. MyBatis는 구성을 위해 간단한 XML 또는 주석을 사용하고 기본 요소, Map 인터페이스 및 Java POJO(Plain Old Java Objects)를 데이터베이스 레코드에 매핑할 수 있다.

Mapped Statements #

Mybatis 의 가장 큰 장점은 매핑된 구문으로, 동일한 기능의 JDBC 코드와 비교하면 약 95% 이상의 코드 수를 감소시키기도 하며 SQL을 작성하는 작업에 집중할 수 있도록 만들어졌다.

  • select - 매핑된 SELECT 구문
  • insert - 매핑된 INSERT 구문
  • update - 매핑된 UPDATE 구문
  • delete - 매핑된 DELETE 구문
  • sql - 다른 구문에서 재사용하기 위한 SQL 조각
  • resultMap - 데이터베이스 결과 데이터를 객체에 불러오는 방법을 정의하는 요소

select #

<select
      id = "selectPerson"
      parameterType = "int"
      parameterMap = "deprecated"
      resultType = "hashmap"
      resultMap = "personResultMap"
      flushCache = "false"
      useCache = "true"
      timeout = "10"
      fetchSize = "256"
      statementType = "PREPARED"
      resultSetType = "FORWARD_ONLY" >
Attribute Description
id 구문을 찾기 위해 사용될 수 있는 명명 공간 내 유일한 구분자
parameterType 구문에 전달될 파라미터의 패키지 경로를 포함한 전체 클래스 명이나 별칭
parameterMap 내부 파라미터 매핑과 parameterType 을 대신 사용하도록 권장
resultType 구문에 의해 리턴되는 타입의 패키지 경로를 포함한 전체 클래스 명이나 별칭
resultMap 외부 resultMap의 참조 명 (MyBatis의 가장 강력한 기능)
flushCache 구문 호출에 대한 캐시 삭제 여부 설정
useCache 구문의 결과를 캐시로 설정
timeout 예외 발생 전까지 요청 결과를 기다리는 최대 시간 설정
(driver dependent)
fetchSize 지정한 수만큼의 결과를 리턴하도록 설정
(driver dependent)
statementType STATEMENT, PREPARED, CALLABLE 중 하나로 선택. MyBatis 에게 statement, PreparedStatement, CallableStatement를 사용하도록 설정
resultSetType FORWARD_ONLY, SCROLL_SENSITIVE, SCROLL_INSENSITIVE, DEFAULT(unset) 중 하나로 선택

insert, update and delete #

<insert
      id = "insertAuthor"
      parameterType = "domain.blog.Author"
      flushCache = "true"
      statementType = "PREPARED"
      keyProperty = ""
      keyColumn = ""
      useGeneratedKeys = ""
      timeout = "20">

<update
      id = "updateAuthor"
      parameterType = "domain.blog.Author"
      flushCache = "true"
      statementType = "PREPARED"
      timeout = "20">

<delete
      id = "deleteAuthor"
      parameterType = "domain.blog.Author"
      flushCache = "true"
      statementType = "PREPARED"
      timeout = "20">
Attribute Description
id 구문을 찾기 위해 사용될 수 있는 명명 공간 내 유일한 구분자
parameterType 구문에 전달될 파라미터의 패키지 경로를 포함한 전체 클래스 명이나 별칭
parameterMap 내부 파라미터 매핑과 parameterType 을 대신 사용하도록 권장
flushCache 구문 호출에 대한 캐시 삭제 여부 설정
timeout 예외 발생 전까지 요청 결과를 기다리는 최대 시간 설정
(driver dependent)
statementType STATEMENT, PREPARED, CALLABLE 중 하나로 선택. MyBatis 에게 statement, PreparedStatement, CallableStatement를 사용하도록 설정
useGeneratedKeys 내부적으로 키를 생성하는 메서드(getGenerateKeys) 사용 여부 설정
(only insert)
keyProperty getGenerateKeys 메서드 혹은 insert 구문의 selectKey 태그에 의해 리턴되는 키를 지정할 property 지정
(only insert)
keyColumn 생성키를 가진 테이블의 컬럼 명을 설정
(only insert)

sql #

<sql id = "userColumns"> id,username,password </sql>

SQL 조각은 다른 구문에 포함할 수 있다.

<select id = "selectUsers" resultType = "map">
    select
    <include refid = "userColumns"></include>
    from some_table t1
    cross join some_table t2
</select>

resultMap #

<resultMap id = "detailedBlogResultMap" type = "Blog">
  <constructor>
    <idArg column = "blog_id" javaType = "int"/>
  </constructor>

  <result property = "title" column = "blog_title"/>

  <association property = "author" javaType = "Author">
    <id     property = "id"       column = "author_id"/>
    <result property = "username" column = "author_username"/>
    <result property = "password" column = "author_password"/>
    <result property = "email"    column = "author_email"/>
    <result property = "bio"      column = "author_bio"/>
  </association>

  <collection property = "posts" ofType = "Post">
    <id     property = "id"      column = "post_id"/>
    <result property = "subject" column = "post_subject"/>

    <discriminator javaType = "int" column = "draft">
      <case value = "1" resultType = "DraftPost"/>
    </discriminator>
  </collection>

</resultMap>
  • constructor - 인스턴스 화 되는 클래스의 생성자에 결과를 삽입하기 위해 사용
    • idArg - id가 되는 인자
    • arg - 그 외 일반적인 결과
  • id - ID result
  • result - 필드 혹은 java bean property에 삽입되는 일반적인 결과
  • association - 복잡한 타입의 연관관계 (1:N)
  • collection - 복잡한 타입의 컬렉션
  • discriminator - 사용할 resultMap을 동적으로 판단
    • case - 몇 가지 값에 기초한 결과 매핑
Attribute Description
id resultMap을 참조하는 데 사용할 수 있는 namespace 고유 식별자
type 정규화된 java 클래스 이름 또는 유형 별칭
autoMapping resultMap에 대한 자동 매핑 활성화 여부 설정

constructor #

<constructor>
    <idArg column = "blog_id" javaType = "int"/>
</constructor>
Attribute Description
column 데이터베이스의 컬럼 명 혹은 별칭 된 컬럼 라벨
javaType 패키지 경로를 포함한 클래스 전체 명이나 타입 별칭
jdbcType 지원되는 타입 목록에서 설명하는 JDBC 타입. Null 입력이 가능한 컬럼에서만 필요
typeHandler 기존의 default typeHandler를 오버라이드하여 재정의
select 컬럼 속성의 값을 매개변수로 하여 다른 매핑 구문의 ID를 통해 해당하는 복잡한 타입의 데이터를 조회
resultMap 인자의 내포된 결과를 적절한 객체로 매핑할 수 있는 ResultMap ID

id, result #

<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
Attribute Description
property 결과 컬럼에 매핑하기 위한 필드 혹은 프로퍼티
column 데이터베이스의 컬럼 명 혹은 별칭된 컬럼 라벨
javaType 패키지 경로를 포함한 클래스 전체 명이나 타입 별칭
jdbcType 지원되는 타입 목록에서 설명하는 JDBC 타입. Null 입력이 가능한 컬럼에서만 필요
typeHandler 기존의 default typeHandler를 오버라이드하여 재정의

association, collection #

<association property="author" javaType="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
</association>

<collection property="posts" 
            javaType="ArrayList" 
            column="id" 
            ofType="Post" 
            select="selectPostsForBlog"/>
Attribute Description
property 결과 컬럼에 매핑하기 위한 필드 혹은 프로퍼티
column 데이터베이스의 컬럼명 혹은 별칭 된 컬럼 라벨
javaType 패키지 경로를 포함한 클래스 전체 명이나 타입 별칭
jdbcType 지원되는 타입 목록에서 설명하는 JDBC 타입. Null 입력이 가능한 컬럼에서만 필요
typeHandler 기존의 default typeHandler를 오버라이드하여 재정의
column 데이터베이스의 컬럼 명 혹은 별칭 된 컬럼 라벨
select 컬럼 속성의 값을 매개변수로 하여 다른 매핑 구문의 ID를 통해 해당하는 복잡한 타입의 데이터를 조회

Reference #

0.0.1_20230725_7_v68