Web/Spring국비지원 수업 정리

<Spring 국비지원 수업> mybatis
깝몬 2023. 8. 10. 00:19

mybatis란?

마이바티스는 자바기반의 프레임워크이며, 자바와 데이터베이스간의 상호작용을 간편하게 해주는 도구이다. xml이나 주석, 매핑등을 이용하여 sql을 정의하는 방식을 이용해 sql의 쿼리작성을 더욱 간편하게 해준다.

 

mybatis를 위한 환경설정

 

1. pom.xml의 dependency

 

  <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.1.0</version>
  </dependency>
  <!-- mybatis-spring : mybatis와  spring를 연결 라이브러리  -->
  <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis-spring</artifactId>
     <version>1.1.0</version>
  </dependency>

이미 추가되어있다면 넣을 필요는 없다.

 

 

2. src의 web.xml

 

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-name>/WEB-INF/spring/action-mybatis.xml</param-name>
    <!-- 원래 있던것 
    <param-value>/WEB-INF/spring/root-context.xml</param-value> -->
</context-param>

원래의 경로에서 변경해주자.

 

 

 

3. root-context와 동일한 위치에 action-mybatis.mxl을 생성 후 내용 입력

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:aop="http://www.springframework.org/schema/aop"
   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
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
<aop:aspectj-autoproxy/>
<!-- 커넥션 풀 설정  -->
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
  <property name="driver" value="${jdbc.driver}" />
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
</bean>

<!-- modelConfig.xml에는
     <typeAlias type="패키지명.클래스명"    alias="클래스별칭"/>지정
      classpath:mybatis/mappers/에는  쿼리문이 있는 xml문서 설정               -->
<bean id="sqlSessionFactory"   class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
        <property name="configLocation"
         value="classpath:mybatis/model/modelConfig.xml" />
      <property name="mapperLocations" value="classpath:mybatis/mappers/*.xml" />
</bean>

<!-- sqlSession이름으로  bean등록 -->
<bean id="sqlSession"
     class="org.mybatis.spring.SqlSessionTemplate">
   <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
</beans>

 

여기에서 property driver 이런 부분은 우리가 이전에 이클립스에서 사용하던 프로젝트 내의 web.xml과 방식이 동일하다.

 	jdbcdriver=com.mysql.cj.jdbc.Driver
	jdbcUrl=jdbc:mysql://localhost:3306/board?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC
	dbUser=root
	dbPass=암호라 생략

이 4가지 항목을 그대로 저곳에 채워주면 된다.

 

 

그리고 

 

action-mybatis.xml에 있던

 

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

이 항목을 보면 resource밑에 mybatis.model.modelConfig.xml과 mybatis.mappers 아래의 xml 파일을 요구하고 있다는것을 알수 있다. 따라서 

 

xml 파일이니 오타주의

 

이러한 경로를 만들어 준후 modelConfig를 작업해보자.

 

<?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>
   
   </configuration>

일단 이 문서 작성의 규칙이 되는 DTD를 이렇게 작성 한 후 

 

mappers 의 아래에도 member.xml을 만든 후 아래의 내용으로 채워주자

 

<?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>

</mapper>

이렇게 한 이유는 mybatis.org라는 곳에서 지정한 양식을 사용 하기 위함이다.

 

 

이제 이 내용물을 채워 우리가 양식을 사용한다.

 

 

MyBatis를 이용한 쿼리문 사용

1. 위에서 정한 modelconfig와  model을 채워보자.

 

먼저 modelconfig이다.

 

<?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="MemberDTO" type="com.myclass.member.domain.MemberDTO"/>
   	</typeAliases>
   </configuration>

Alias는 우리가 DB에서 했듯이 별칭으로 줄여서, 혹은 다른방식으로 언급 할 수 있는 방식이다.

 

다음으로 model이다.

 

<?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="member">
	<!-- 회원수 조회 -->
	<select id="countMember" resultType="int">
	<![CDATA[
	select count(no)
	from member
	]]>
	</select>
	
	
	<!-- 목록 조회 -->
	<select id="showAllMember" resultType="java.util.Map">
	<![CDATA[
	select *
	from member
	]]>
	</select>

</mapper>

 

이러한 양식과 결과물에 대한 언급 및 아이디를 만들어주고, member라는 table에 대한 작성이니 namespace를 member로 작성한다.

 

 

 

이제 이것을 활용하는 클래스를 만들어보자.

 

package com.myclass.repository;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


@Repository
public class MemberRepositoryImpl {
	
	@Autowired
	private SqlSession sqlSession;
	
	public int countAllMember() {
		int totalMemberCnt = sqlSession.selectOne("member.showAllMember");
		return totalMemberCnt;
	}
}

@Repository를 작성함으로서 스프링 프레임워크의 영향을 받는 Repository가 되는 것이고,

 

Autowired를 통해 sqlSession을 생성후

 

그것을 이용해 아까의 member.xml의 것을 

 

sqlSession.selectOne("namespace명.쿼리문id");

형식에 맞추어 사용한다.