본문 바로가기
Java Web Programming/6. Spring | MyBatis

[SpringMVC/MyBatis] SpringMVC + 마이바티스 연동 연습 1

by 파프리카_ 2020. 11. 9.
728x90
반응형

MyBatis와 Spring 연동에 대한 포스팅


[ SpringMVC와 MyBatis 프레임워크의 동작 프로세스 ]

 

[ MyBatis & Spring Framework Relationship ] 

출처 : https://terasolunaorg.github.io


Maven pom 설정 

 

/pom.xml

<dependencies>
  <!-- Spring-Web MVC Framework (SpringMVC, IOC, DI/DL) -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.14.RELEASE</version>
  </dependency>

  <!-- Ajax JSON Library (jackson-databind) -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
  </dependency>
  
  <!-- MyBatis Framework -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.0</version>
  </dependency>

  <!-- Spring과 MyBatis 연동 Framework -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
  </dependency>

  <!-- DBCP ver.2 -->
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1.1</version>
  </dependency>

  <!-- JDBC(*Spring ver과 같아야한다) -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.14.RELEASE</version>
  </dependency>
  
  <!-- JSTL Library-->
  <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
  </dependency>

</dependencies>

 

DD (Deploytment Descriptor) 설정

 

/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>SpringMVC4-MyBatis</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <!-- request에 대한 한글처리 -->
  <filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Spring configure 설정

 

* namespace에서 context,  mvc 체크

 

1. DBCP 설정

2. SqlSessionFactory 설정

3. SqlSessionTemplate설정

4. IOC 설정 : <context:component-scan> :  IOC, DI, DL에 대한 설정

5. SpringMVC 설정

6. ViewResolver 설정 : client에게 응답하는 view에 대한 설정

 

/springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">

	<!-- DBCP 정의 -->
	<bean id="dbcp" class="org.apache.commons.dbcp2.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe"/>
		<property name="username" value="scott"/>
		<property name="password" value="tiger"/>
	</bean>
	
	<!-- MyBatis와 Spring 연동 설정-->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- DBCP(datebase connection pool) 주입 -->
		<property name="dataSource" ref="dbcp"/>
		<!-- MyBatis에서 쓸 mapper loation(path) 주입 -->
		<property name="mapperLocations" value="classpath:/mybatis/config/*.xml"/>
		<!-- Package에 별칭주기 -->
		<property name="typeAliasesPackage" value="org.kosta.model"/>
	</bean>
	
	<!-- MyBatis + Spring 연동 시,
		 개발 생산성을 위해 SqlSessionTemplate 클래스를 이용
		 SqlSessionTemplate은 선언적 방식의 트랜잭션 제어를 지원
		 (= AOP 기반 Transaction 제어)-->
	<bean id="SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactoryBean"/>
	</bean>
	
	<!-- IOC 설정 -->
	<context:component-scan base-package="org.kosta"></context:component-scan>

	<!-- SpringMVC 설정 : annotation 기반 controller 설정 -->
	<mvc:annotation-driven/>
	
	<!-- ViewResolver 설정 : client에게 응답하는 view에 대한 설정 -->
	<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<bean id="customerDAO" class="org.kosta.model.CustomerDAOImpl">
		<constructor-arg ref="SqlSessionTemplate"/>
	</bean>	
</beans>

mapper (/mybatis.config)

 

/customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Sql Mapper -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="customer">
 	<select id="getCustomerTotalCount" resultType="int">
 		SELECT COUNT(*)
		FROM   spring_customer
 	</select>
 	
 	<select id="findCustomerById" resultType="customerVO" parameterType="string">
 		SELECT id, name, address
 		FROM   spring_customer
 		WHERE  id=#{value}
 	</select>
 	
</mapper>

SQL

1. 테이블 생성 및 값 입력

CREATE TABLE spring_customer(
    id      VARCHAR2(100) PRIMARY KEY,
    name    VARCHAR2(100) NOT NULL,
    address VARCHAR2(100) NOT NULL
)

INSERT INTO spring_customer VALUES('java', '초코초코', '대만');

Model

/org.kosta.model

 

/CustomerVO.java

package org.kosta.model;

public class CustomerVO {
	private String id;
	private String name;
	private String address;
	
	public CustomerVO() {
		super();
	}

	public CustomerVO(String id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "CustomerVO [id=" + id + ", name=" + name + ", address=" + address + "]";
	}
}

/CustomerDAO.java <<interface>>

package org.kosta.model;

public interface CustomerDAO {

	int getCustomerTotalCount();
	
	CustomerVO findCustomerById(String id);
}

 

-- annotation --

@Repository 

@Resource

 

/CustomerDAOImpl.java

package org.kosta.model;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class CustomerDAOImpl implements CustomerDAO {
	
	//MyBatis SQL 실행 메서드를 제공하는 객체
	@Resource //DI(의존성 주입): spring container로부터 객체를 주입
	private SqlSessionTemplate template;
	
	public CustomerDAOImpl(SqlSessionTemplate template) {
		super();
		this.template = template;
	}
	
	//getCustomerTotalCount: 전체 고객 수 찾기
	@Override
	public int getCustomerTotalCount() {
		return template.selectOne("customer.getCustomerTotalCount");
	}
	
	//findCustomerById : id로 회원정보 찾기
	@Override
	public CustomerVO findCustomerById(String id) {
		return template.selectOne("customer.findCustomerById", id);
	}
	
}

View

/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>home</title>
</head>
<body>
	<h3>SpringMVC와 MyBatis Framework 연동</h3>
	<a href="getCustomerTotalCount.do">총 고객 수 확인</a>
	<hr>
	<form action="findCustomerById.do">
		아이디 <input type="text" name="id" required="required">
		<input type="submit" value="검색">
	</form>
</body>
</html>

/views

 

/customer-totalcount.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>total count</title>
</head>
<body>
	총 고객 수 : ${requestScope.totalCount} 명
</body>
</html>

 

/find-ok.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>고객 정보 검색 결과</title>
</head>
<body>
	고객 아이디 : ${requestScope.customerVO.id} <br>
	고객명 : ${requestScope.customerVO.name} <br>
	고객 주소: ${requestScope.customerVO.address} 
</body>
</html>

 

/find-fail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<script type="text/javascript">
	alert("${param.id}에 해당하는 고객정보가 없습니다.");
	location.href="index.jsp";
</script>

Controller

/org.kosta.Controller

 

-- annotation --

@Controller

@Resource

@RequestMapping

 

/CustomerController.java

package org.kosta.controller;

import javax.annotation.Resource;

import org.kosta.model.CustomerDAO;
import org.kosta.model.CustomerVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController {
	@Resource
	private CustomerDAO customerDAO;

	// 전체 고객 수 반환
	@RequestMapping("getCustomerTotalCount.do")
	//방법 1) ModelAndView
	public ModelAndView getCustomerTotalCount() {
		int totalCount = customerDAO.getCustomerTotalCount();
		//new ModelAndView(view-name, attribute-name, attribute-value)
		return new ModelAndView("customer-totalcount", "totalCount", totalCount);
	}
	
	//방법 2) Model
	public String getCustomerTotalCount2(Model model) {
		int totalCount = customerDAO.getCustomerTotalCount();
		model.addAttribute("totalCount", totalCount);
		return "customer-totalcount";
	}
	
	// id로 회원정보 찾기
	@RequestMapping("findCustomerById.do")
	public String findCustomerById(String id, Model model) {
		String viewName = null;
		CustomerVO vo = customerDAO.findCustomerById(id);
		if (vo != null) {	
			viewName = "find-ok";
			model.addAttribute("customerVO", vo);
		} else {
			viewName = "find-fail";
		}
		return viewName;
	}
}

[ 결과 ]

> 홈화면 (index.jsp)

 

> '총 고객 수 확인' 클릭하면, customer-totalcount.jsp로 이동

 

> DB에 있는 아이디를 입력하면, find-ok.jsp로 이동

 

>  DB에 없는 아이디를 입력하면, find-fail.jsp로 이동하여 alert이 뜬 후, index.jsp로 이동

 

728x90
반응형