Cohe

MyBatis 스프링 연동 본문

Spring, SpringBoot

MyBatis 스프링 연동

코헤0121 2024. 4. 19. 17:17
728x90

MyBatis 스프링 연동

  • spring-jdbc와 같은 라이브러리를 이용해서 구현할 수도 있다. ⇒ templete라는 녀석이 있다.
  • MyBatis: sql를 거의 유사하게 사용할 수 있다.
  • JPA 프레임워크는 객체 타입의 프로그래밍에 더 가깝다.
  • 마이바티스를 다운 받는다

mybatis – 마이바티스 3 | 소개

  • 마이바티스는 단독 개발이 가능하다. → spring에 dao를 작성해서 처리하는 방식
  • 마이바티스와 스프링을 연동하여 mapper 인터페이스만 이용하는 방식 : MyBatis-spring이라는 라이브러리를 사용해야 한다
  • build.gradle 작업
    • spring-jdbc가 필요하다.+ maven에서 다운받음
  //spring jdbc 설치
  implementation group: 'org.springframework', name: 'spring-jdbc', version: '5.3.34'
  implementation group: 'org.springframework', name: 'spring-tx', version: '5.3.34'
  
  // <https://mvnrepository.com/artifact/org.mybatis/mybatis>
  implementation group: 'org.mybatis', name: 'mybatis', version: '3.5.16'
// <https://mvnrepository.com/artifact/org.mybatis/mybatis-spring>
  implementation group: 'org.mybatis', name: 'mybatis-spring', version: '3.0.3'

  • 의존성 주입 : 멤버, 생성자, setter ⇒ setter 주입
    • root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">


    <!--    <bean class="com.testjsp.demotest.sample.SampleDAO"></bean>-->
    <!--    <bean class="com.testjsp.demotest.sample.SampleService"></bean>-->

    <!-- 컴포넌트 스캔 : 특정 위치에 있는 bean들을 자동으로 등록합니다.
            이때 객체에 어노테이션을 사용하게 됩니다.
            사용하는 어노테이션 : @Controller
                             @Service
                             @Repository
                             @Component -->

    <context:component-scan base-package="com.zercok.demotest2.sample"/>
    <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/webdb?serverTimezone=Asia/Seoul"></property>
        <property name="username" value="spring"></property>
        <property name="password" value="spring"></property>
        <property name="dataSourceProperties">
            <props>
                <prop key="cachePrepStmts">true</prop>
                <prop key="prepStmtCacheSize">250</prop>
                <prop key="prepStmtCacheSqlLimit">2048</prop>
            </props>
        </property>

    </bean>
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <constructor-arg ref="hikariConfig" />
    </bean>
    <!-- 마이바틱스 사용을 위한 객체 생성 : SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /> 
    </bean>
</beans>
  • connection 객체를 생성하듯 SqlSessionFactory를 생성해야 한다 → 마이바틱스를 사용하기 위해서

  • 매퍼 인터페이스를 같이 결합할 때 과정
    1. 매퍼 인터페이스 정의 메소드 선언
    2. 해당 xml 파일을 작성(이름 같게!) → <select> 태그 사용(sql을 태그로 사용)
    3. 각 태그의 id 값→메소드 명

스프링 MVC 기초

  • 핵심은 의존성 주입
  • 그 다음은 MVC2 (=web mvc2)
    • 모든 요청을 frontController을 통해 나아가기 때문에 frontController 패턴이라고 한다.
    • 스프링 MVC에서는 DispatcherServlet이라는 객체가 프론트 컨트롤러의 역할을 수행
  • 파라미터 자동 수집과 변환
    • 자동으로 파라미터를 수집한다.
    • 자동 형변환 처리가 가능하다.
    • 객체 자료형의 경우 set 메서드를 사용해서 동작이 실행됨 → 기본생성자가 반드시 필요하다.(Java Bean)
  • 스프링 반환타입
    • void의 경우 uri 경로에 값으로 DispatcherServlet에게 전달
    • 반환 타입이 String인 경우에는 문자열의 값을 DispatcherServlet에게 전달
      • uri : 식별자만, url은 식별자+위치
      • String 반환은 : 디스패쳐 서블릿으로 반환 → view 리졸브에 보내줌 → url 주소를 담게 됨
      • → redirect 사용시, forward : 포워드 사용(잘 사용 x)
    • 반환타입이 객체나 배열, 기본 자료형
      • 객체는 객체 타입에 따라 달라짐
      • 기본 자료형은 다른 방법으로 받는다 → responseEntity로 받아서 값을 받는다 ⇒ RESTful 방식을 쓴다.