상세 컨텐츠

본문 제목

Mybatis 이용(스프링과 연결)

JAVA/Mybatis

by 영공쁘이 2021. 8. 10. 14:36

본문

정의: Mybatis는 JDBC 코드 등을 SQL, 저장 프로시저와 몇가지 고급 매핑을 할 수 있도록 지원하는 프레임워크다.

       그러면서 JAVA 환경에서도 SQL과의 접근이 더 쉬워짐을 알 수 있다.

 

MyBatis를 사용하기 앞서, 3가지의 설정이 필요하다.

1. pom.xmlMyBatis와 MyBatis와 연계될 스프링 JDBC 설정하기

		<!-- MyBatis -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.2.8</version>
      </dependency>

      <!-- mybatis-spring -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis-spring</artifactId>
         <version>1.2.2</version>
      </dependency>

      <!-- Mysql -->
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>5.1.31</version>
      </dependency>

      <!--spring-jdbc -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>3.2.3.RELEASE</version>
      </dependency>

 

2. XML에서 sqlSessionFactory 빌드하기

 

  1) sqlSessionFactory: Mysql서버 Mybatis를 연결하는 객체(이 객체가 DataSource를 참조하여 이어주는 것이다)

   mybatis-config.xml 파일을 추가함으로써 매핑시킬 주체(앞으로 할 프로그램에 대해서는, board.xml, member.xml)를     선언할 수 있다(곧 매핑시킬 수 있음을 나타냄)

 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation"
        value= "classpath:/mybatis/mybatis-config.xml">
    </property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory"></constructor-arg>
</bean>

 - 아래는 mybatis-config.xml 이다.

<?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>
	<typeAliases>
	  <typeAlias alias="member77" type="co.kr.Hello.dto.MemberDTO"/>
	  <typeAlias alias="Board77" type="co.kr.Hello.dto.BoardDTO"/>
	</typeAliases>

<!-- vo, DTO에 alias(별칭) 이름을 달아주고 mybatis에 설정만 해주면 
resultType으로 alias 이름을 그대로 사용할 수 있다. -->

	<mappers>
		<mapper resource="/mybatis/member.xml"/>
		<mapper resource="/mybatis/board.xml"/>
	</mappers>
	
</configuration>

 - DTO이름이 길어지면 코딩을 하고 읽기에 불편함이 있을 수 있는데, typealias를 통해서 보다 간결하고 쉽게 사용이 가능함(>DTO이름이 길어도 별칭으로 사용할 수가 있기 때문!) 

- mappers tag로 앞서 호출할 xml파일을 가져온다.(이로써 mybatis와 연관 관계를 맺는다.)

 

2) sqlSessionFactory 객체는 sqlSession 인스턴스를 만들 수 있다.

그래서 컨트롤러에서 sqlSession.함수 명 이런식으로 보다 접근을 쉽게 할 수가 있게 되었다.

 

3) namespace: 인터페이스 연결이 가능하고 코드를 줄일 수 있으며 매핑이 가능하도록 구문을 만들 수 있다.

<mapper namespace="board">
	
	<!-- 최대 글번호 얻기 -->
	<select id="numMax" resultType="Integer">
		select max(num) from board
	</select>
 </mapper>

namespace는 Mapper XML의 namespace와 일치해야 하는 것을 주의하자. SqlSession의 구문을 실행하는 메서드는 selectOne, selectList, select, selectMap, insert, update, delete가 있다. selectOne 메서드는 한 개 이상의 객체나 null이 return된다면 예외가 발생하므로, 객체가 얼마나 리턴될지 모른다면 selectList 메서드를 사용해야 한다. insert, update, delete 메서드에 의해 리턴되는 값은 실행된 구문에 의해 영향을 받은 레코드수를 표시한다

 

 

총평:

 기존에는 프로젝트에서, 자바 매핑 어노테이션을 이용해서 보다 코드를 간결하게 사용을 했다.(DI로, @Autowired 사용)

 하지만 이번 sts를 이용하면서 어노테이션을 이용하되, 이것은 sqlSession을 추가할 뿐이고.

 실제로 컨트롤러에서 Namespace를 이용하면서 필요한 id만 가져와 쓸 수 있다는 것이 큰 장점이다.

이들은, 보다 코드도 간결해지고 사용이 편하다.

'JAVA > Mybatis' 카테고리의 다른 글

sql구문매핑할것예시(첨가사항예제)  (0) 2021.08.07

관련글 더보기