Basic In Mybatis

풀어갈 나의 이야기·2021년 12월 4일
0

JAVA

목록 보기
2/7
post-thumbnail

목차

mybatis 정의
mybatis 사용법
mybatis 문법
Refference

Mybatis 란?

  • Wiki
    • 마이바티스는 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크이다. 마이바티스는 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해준다. 마이바티스는 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해 XML과 애노테이션을 사용할 수 있다.
  • Real
    • 객체지향 언어인 자바의 관계형 데이터 베이스 프로그래밍을 좀더 쉽게 할수 있게 도와주는 개발 프레임워크이다.
    • 자바는 jdbc api 를 제공해주지만, 이런 JDBC를 이용하면 1개 클래스에 반복된 코드가 존재, 한 파일에 java언어와 sql언어가 있어서 재사용성 등이 안좋아지는 단점이 있다.

특징

  • 한 두줄의 자바 코드로 DB 연동을 처리
  • SQL 명령어를 자바 코드에서 분리해 XML 파일에 따로 관리
  • 결론 : MyBatis는 JDBC를 보다 편하게 사용하기 위해 개발되었다.

Ibatis와 Mybatis의 차이

  • Ibatis 는 아파치 프로젝트였을때의 구버전, 구글로 넘어가면서 Mybatis 로 이름만 바뀜
IbatisMyBatis
최소 JDK 버전1.41.5
패키지 구조com.ibatis.*org.mybatis
SqlMap.xml에서 변경사항parameterMapparameterType
엘리먼트 명칭 변경사항SqlMapConfig SqlMapConfiguration mapper
네임스페이스 속성선택필수

구조

  • 주요 구성 요소
    • Mybatis configuration file
      • DB의 연결대상, 매핑 파일의 경로, 작업설정과 같은 세부사항을 설정하는 파일
      • Spring 과 통합하여 사용할 때 데이터베이스의 연결 대상과 매핑 파일경로 설정을 구성파일에 저장할 필요는 없음
    • SqlSessionFactoryBuilder
      • 설정파일을 읽어서 SqlSessionFactory객체를 생성
      • mybatis 의 구성파일을 읽고 생성하는 SqlSessionFactory 구성요소
      • Spring 과 통합되어 사용할 때 어플리케이션 클래스에서 직접 처리하지는 않음
    • SqlSessionFactory
      • SqlSession을 만드는 역할
      • SqlSession 을 생성하는 구성요소
    • SqlSession
      • sql문을 실제 호출해주는 역할(필요시 open하고 close를 해줘야 한다.)
      • SQL 실행 및 트랜잭션 제어를 위한 API를 제공하는 구성요소
    • Mapper Interface
      • SQL 을 호출하는 인터페이스
      • mybatis는 Mapper 인터페이스에 대한 구현 클래스를 자동으로 생성하므로, 개발자는 인터페이스만 생성하면 됨

Mybatis 사용

dependency 추가

  • mybatis와 mybatis를 연동하는 스프링 그리고 스프링과 jdbc를 연결하는 라이브러리이다.
  • mybatis는 필연적으로 데이터베이스를 이용하는 sql문을 설정하는 라이브러리 이다.
    • 데이터베이스 개발환경이 꼭 필요하고 스프링 jdbc와 그를 연결하는 mybatis-spring 라이브러리가 필요하다.
<!-- MyBatis, MyBatis-Spring, Spring-JDBC -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
</dependencies>

Context.xml 에 설정 (기본만.. 실제 Billing 등의 프로젝트는 xml 이 세분화 되어있음)

  • Spring 에서 관리하는 Bean 을 만드는 것
<bean id="dataSource"
      name="dataSource"
      class="oracle.jdbc.pool.MysqlDataSource">
    <property name="URL"
              value="jdbc:mysql:thin:@localhost:1521" />
    <property name="user" value="" />
    <property name="password" value="" />
</bean>

<bean id="sqlSessionFactory"
      name="sqlSessionFactory"
      class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation"
              value="classpath:/mybatis-config.xml" />
    <property name="mapperLocations"
              value="classpath:/mappers/*.xml" />
</bean>

<bean id="sqlSession" name="sqlSession"
      class="org.mybatis.spring.SqlSessionTemplate"
      destroy-method="clearCache">
    <constructor-arg name="sqlSessionFactory"
                     ref="sqlSessionFactory" />
</bean>

mybatis-config.xml 생성

  • 실제 현업 프로젝트는 를 통해 package를 묶는다.
  • 모델 클래스 경로를 지정해주고, 모델 객체도 컬럼이름과 맞춰주어서 사용한다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="tblMember" value="tbl_member"/>
        <property name="tblBoard" value="test_board" />
        <property name="colBno" value="bno" />
        <property name="colTitle" value="title" />
        <property name="colRegdate" value="regdate" />

        <property name="colEmail" value="email"/>
    </properties>

    <typeAliases>
        <package name="edu.spring.ex02.domain" />
    </typeAliases>

</configuration>

Mapper XML 작성

  • 설정한대로 테이블이나 컬럼이름대로 사용하기 위해선 ${name} 이렇게 사용하면 되고, 개발자가 직접 코드로 채워넣어야 하는 경우 #{name} 이런식으로 사용한다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="edu.spring.ex02.mappers.MemberMapper">

    <select id="selectAll" resultType="Member">
    SELECT * FROM ${tblMember}
    </select>

</mapper>

인터페이스를 이용한 방법

  • 현재 사용되는 프로젝트의 구조는 Repository 클래스에서 Mapper Interface에 정의된 함수를 호출한다.
@Repository
public class ProductRepository {

    @Autowired
    private ProductMapper productMapper;

     public <List<Product>> findAll() {
        return productMapper.findAll());
    }

--------------------

public interface ProductMapper {
    List<Product> findAll();
  • 코드의 구조를 위와같이 맞추고, ProductMapper.xml 에 다음과 같이 설정한다.
<select id="findAll"
        resultType="Product">
    SELECT
        <include refid="Product" />
    FROM
        product
</select>

Mybatis 문법

mapper xml

select

  • 이 구문의 이름은 selectPerson이고 int타입의 파라미터를 가진다. 그리고 결과 데이터는 HashMap 에 저장된다.
<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>
  • 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">

주요 속성

  • id
    • 해당 구문을 호출할 때 사용되는 값으로, SQL문을 구분하는 유일한 식별자 (필수)
  • parameterType
    • 구문에 전달될 파라미터의 패키지 경로를 포함한 전체 클래스나 별칭
  • resultType
    • 구문이 리턴하는 타입의 클래스나 별칭
  • flushCache
    • 이 속성값이 true 이면 구문이 호출될 때마다 캐시가 지워짐
  • useCache
    • 이 속성이 true 이면, 구문의 결과가 캐싱됨
  • * 이 요소는 다른 구문에서 재사용 가능한 SQL 구문을 정의할 때 사용한다.
    *
<sql id="userColumns"> id, username, password </sql>
<select id="selectUsers resultType="map">
  select <include refid="userColumns" />
</select>

동적 SQL

if

  • 동적 SQL에서 가장 공통적으로 사용, where 의 일부로 포함시킬수 있음
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

choose

  • 자바에서는 switch 구문과 유사하며 마이바티스에서는 choose 엘리먼트를 제공한다
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

foreach

  • 동적 SQL 에서 공통적으로 필요한 것은 collection 에 대해 반복처리를 하는 것이다. 종종 IN 조건을 사용하게 된다.
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

refference
https://mybatis.org/mybatis-3/ko/index.html (document 페이지)
https://araikuma.tistory.com/475
https://blog.naver.com/rla8860/220671456438
https://sjh836.tistory.com/127
https://universecoding.tistory.com/42

profile
깨끗한 스케치북 일수록 우아한 그림이 그려지법, 읽기 쉽고, 짧은 코드가 더 아름다운 법.. 또한 프로그래머의 개발은 구현할 프로그래밍이 아닌, 풀어갈 이야기로 써내려가는것.

0개의 댓글