티스토리 뷰

728x90
  • MyBatis는 기존의 SQL을 그대로 활용할 수 있다는 장점이 있고, 진입장벽이 낮은 편이어서 JDBC 대안으로 많이 사용
  • MyBatis-spring 이라는 라이브러리를 통해 쉽게 연동작업 처리 가능
  • MyBatis-Spring <--> MyBatis <--> DB
  • MyBatis는 자동 close 기능이 있어 따로 close를 해주지 않아도 된
pom.xml 추가
 <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
  <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
  </dependency>

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework-version}</version>
  </dependency>

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework-version}</version>
  </dependency>   


  root-context.xml 에 추가
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
   </bean>    
  • Sqlsseion Test Code
import java.sql.Connection;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class DataSourceTests {

    @Autowired
    private DataSource ds;

    @Autowired
    private SqlSessionFactory sessionFactory;


    @Test
    public void testConnection2() {

        try(SqlSession sseion = sessionFactory.openSession();
                Connection con = sseion.getConnection()){
            log.info(sseion);

        }catch(Exception e) {
            e.printStackTrace();
        }
    }

}

스프링과 연동 처리

  • SQLSessionFactory를 이용해서 코드를 작성해도 직접 Connection을 얻어서 JDBC코딩이 가능하지만, 좀 더 편하게 작업하기 위해
  • SQL을 어떻게 처리할 것인지를 별도의 설정으로 분리해 주고, 자동으로 처리되는 방식을 이용하는 것이 좋다.
  • 이를 위해 MyBatis의 Mapper라는 존재를 작성함
  • Mappbe는 SQL과 그에 대한 처리를 지정하는 역할
  • MyBatis-Spring을 이용하는 경우 Mapper를 XML과 interface + annotation 형태로 작성할 수 있음
4.2.1 Mapper인터페이스
  • 패키지 생성 후 TimeMapper Interface 생성
  • TimeMapper Interface에 MyBatis의 Annotation을 이용해서 SQL을 메서드에 추가
  • import org.apache.ibatis.annotations.Select; << MyBatis의 Select를 Anntation 해주면 된다
  • MyBatis 사용할 때 가장 중요 한것 ;(세미콜론) 없어야 한다
    public interface TimeMapper {
    // 시스템상 현재 시간 가져오기
    @Select("SELECT sysdate FROM dual")
    public String getTime();
    }
  • 이런 식으로 매우 간단히 DB 연결 가능
    1. TimeMapper 인터페이스를 정의한다.
    1. @Select 어노테이션을 사용하여 SQL 쿼리를 작성한다. 해당 쿼리는 Oracle 데이터베이스에서 sysdate를
      가져오는 쿼리이다.
    1. getTime() 메서드를 호출하면, MyBatis가 해당 쿼리를 실행하고 결과값인 현재 날짜 및 시간을 문자열 형태로
      반환한다.
    1. 이때, MyBatis 설정 파일에서 해당 인터페이스를 매핑해줘야 한다. MyBatis 설정 파일에서 인터페이스와
      SQL 쿼리를 매핑하고, 데이터베이스 연결 정보를 설정한다.
    1. getTime() 메서드를 사용하여 현재 날짜 및 시간을 가져올 수 있다.
  • Mapper를 작성해 주었다면 MyBatis가 동작할 때 Mapper를 인식할 수 있도록 root-context.xml에 추가 설정.
    가장 간단한 방식 <#mybatis:scan> 태그 이용
  • 예제처럼 자동으로 mapper 패키지를 인식하는 방식으로 작성 하는 것이 편리
  • mapper를 mybatis가 인식을 할 수 있도록 설정
  • root-context에 namespaces 탭에 mybatis-spring 추가
  • 추가하면 자동완성 기능 제공
  • xmlns:mybatis-spring="[http://mybatis.org/schema/mybatis-spring](http://mybatis.org/schema/mybatis-spring)" << Source
    맨 윗부분 <beans에 해당 코드 있는지 확인
  • <mybatis-spring:scan base-package="org.codehows.mapper"/> Source 밑 부분에 코드 추가
  • mybatis와 spring을 연동 시키는 코드

4.2.2 Mapper 테스트 - - 굉장히 중요

  • MyBatis-Spring은 Mapper 인터페이스를 이용해서 실제 SQL 처리가 되는 클래스를 자동 생성
  • 개발자들은 인터페이스와 SQL만을 작성하는 방식으로도 모든 JDBC 처리를 끝낼 수 있음
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.codehows.mapper.TimeMapper;

import lombok.Setter;
import lombok.extern.log4j.Log4j;


// 인터페이스로 테스트 진행
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class TimeMapperTests {

    @Setter(onMethod_ = @Autowired)
    private TimeMapper timeMapper;

    @Test
    public void testGetTime() {
        log.info(timeMapper.getClass().getName());
        log.info(timeMapper.getTime());
    }
}
  • WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector -
    (file:/C:/Users/codepc/.m2/repository/org/mybatis/mybatis/3.4.6/mybatis-3.4.6.jar) to method java.lang.String.value()
    WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
    WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
    WARNING: All illegal access operations will be denied in a future release
    해당 오류.. 보통 버전 문제로 mybatis 3.4.2 -> 3.5.2로 하고 난 뒤 해결 됨
Mapper인터페이스의 설정확인
XML Mapper + Mapper 인터페이스
  • 인터페이스가 기준
  • 23-3-22 재설정 함.

4.2.3 XML 매퍼와 같이 쓰기

  • XML 파일 설정 -> src/main/resources new -> Folder(org) -> Folder( org. 뒤에 올 폴더 이름 ) -> Folder -> mapper
    • Folder 생성시 폴더 하나 하나 생성 해야 나중에 오류 생기지 않음
  • XML의 이름은 인터페이스랑 똑같이 해주는 것이 나중에 찾기 쉽고 처리하기도 쉽다
  • dtd가 있으면 자동 완성 기능 제공
  • TimeMapper.xml 작성

```

  • Annotation을 사용하는 방법이 압도적으로 편리하지만 SQL이 길어지거나 복잡해지는 경우에는 XML을 이용하는
    방식 선호
  • Mapper와 XML을 같이 이용해보기 위해 기존의 TimeMapper 인터페이스에 추가적인 메서드 작성
    • import org.apache.ibatis.annotations.Select;
      public interface TimeMapper {
      // 시스템상 현재 시간 가져오기
      //간단한 쿼리문을 어노테이션으로 처리 함 //디비 연결 간단하게
      //; 없어야 한다
      @Select("SELECT sysdate FROM dual")
      String getTime();
      String getTime2();
  • XML 설정
    • \\SELECT sysdate FROM dual
  • log4jdbc-log4j2 설정
  • MyBatis는 내부적으로 PreparedStatement를 이용하기 때문에 좀 더 쉽게 SQL의 로그를 보기 위한 설정
  • --> DB 버전이 맞지 않으면 오류가 많이 생김 조심!
  • 개발 된지 오래 되었기 때문에
  • 라이브러리 추가
    • 설정
      • DataSource 설정 변경
      • 102페이지의 프로퍼티 파일을 반드시 추가
      • log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator <<
      • src/main/resources 에 log4jdbc.log4j2.properties 추가. main에 추가 할 때 test에도 같이 추가 해주면 좋다
    • <property name ="driverClassName"
      \value="net.sf.Log4jdbc.sql.jdbcapi.DriverSpy">
      -- 이런 것들을 타이핑 할 때는 복사 붙여넣기를 활용하는 것을 버릇화 하자
    • <property name="jdbcUrl" -- **jdbc:oracle:thin:@localhost:1521:XE << jdbc랑 oracle 사이에 Log4jdbc 입력
  • root-context.xml 에 추가 or 수정 하기
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">

    <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"> </property>
    <property name="jdbcUrl" value="jdbc:log4jdbc:oracle:thin:@localhost:1521:XE"></property>
    <property name="username" value="book_ex"></property>
    <property name="password" value="book_ex"> </property>

</bean>
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함