티스토리 뷰

Programming/Java

Spring - Mybatis이용 DB 연동

파란크리스마스 2016. 11. 19. 19:40
728x90

출처 : mybatis-spring – 마이바티스 스프링 연동모듈 | 매퍼 주입

DB 접속 설정(WebContent\WEB-INF\iot-datasource.xml)

데이터베이스 접속 정보(JDBC) 설정
JDBC는 각 데이터베이스 마다 제공되고 있고, 연결방식도 달라 따로 검색이 필요

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<!-- ========================= Resource Definitions ========================= --> 
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/iot_db?user=iot&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull"/>
		<property name="username" value="iot"/>
		<property name="password" value="iot"/>
		<property name="maxActive" value="20"/>
		<property name="maxIdle" value="5"/>
		<property name="maxWait" value="2000"/>
		<property name="validationQuery" value="select 1"/>
		<property name="testWhileIdle" value="true"/>
		<property name="timeBetweenEvictionRunsMillis" value="7200000"/>        
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>	

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="transactionFactory">
			<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
		</property>
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
</beans>

DB 접속정보 iot-servlet.xml에 추가

    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-datasource.xml" />

MyBatis Domain 패키지 생성

MyBatis Mapper 패키지 생성

MyBatis Service 패키지 생성

MyBatis 설정 파일 작성(WebContent\WEB-INF\iot-mybatis.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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
    <!-- enable component scanning (beware that this does not enable mapper scanning!) -->   
    <context:component-scan base-package="com.iot.db.service" />
         
    <!-- enable autowire -->
    <context:annotation-config />
 
    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven />
 
    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.iot.db.domain" />
    </bean>
 
    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.iot.db.mapper" />
    </bean>
</beans>

user_info 예제 테이블 생성

CREATE TABLE `user_info` (
  `user_id` varchar(20) NOT NULL,
  `password` varchar(20) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `nickname` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
);

INSERT INTO `user_info` (`user_id`, `password`, `name`, `nickname`) VALUES
  ('test1', '1111', 'test1', NULL),
  ('test2', '1111', 'test2', NULL),
  ('test3', '1111', 'test3', NULL);

MyBatis Domain 클래스 생성

package com.iot.db.domain;

public class UserInfo {

	// pk
	private String user_id;

	private String password;
	private String name;
	private String nickname;

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public String getUser_id() {
		return this.user_id;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return this.password;
	}

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

	public String getName() {
		return this.name;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getNickname() {
		return this.nickname;
	}
}

MyBatis Mapper 인터페이스 생성

package com.iot.db.mapper;

import java.util.List;

import com.iot.db.domain.UserInfo;

public interface UserInfoMapper {

	public List<UserInfo> listUserInfo();

}

MyBatis Mapper 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 namespace="com.iot.db.mapper.UserInfoMapper">

	<!-- listUserInfo -->
	<select id="listUserInfo" parameterType="map" resultType="com.iot.db.domain.UserInfo">
		select *
		  from user_info
	</select>

</mapper>

MyBatis Service 클래스 생성

package com.iot.db.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iot.db.domain.UserInfo;
import com.iot.db.mapper.UserInfoMapper;

@Service
public class UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	public List<UserInfo> listUserInfoFormData() throws Exception {
		return userInfoMapper.listUserInfo();
	}

}

컨트롤러 클래스 수정

서비스로 사용자리스트를 조회해서 modelMap에 사용자리스트(userlist)를 설정

package com.iot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iot.db.domain.UserInfo;
import com.iot.db.service.UserInfoService;

@Controller
public class IotController {

	@Autowired
	private UserInfoService service;

	@RequestMapping(value = "/hello_world.iot", method = RequestMethod.GET)
	public String hello_world(ModelMap modelMap) throws Exception {
		List<UserInfo> userlist = service.listUserInfoFormData();
		modelMap.addAttribute("userlist", userlist);
		return "/hello_world";
	}

}

hello_world.jsp에 데이터 전달

컨트롤러에서 전달받은 사용자리스트(userlist)를 반복해서 사용자정보를 출력

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

Hello World

<p></p>
<table border="1">
	<c:forEach items="${userlist}" var="data" varStatus="loop">
		<tr>
			<td>${data.user_id}</td>
			<td>${data.password}</td>
			<td>${data.name}</td>
			<td>${data.nickname}</td>
		</tr>
	</c:forEach>
</table>

</body>
</html>

실행결과

MyBatis 설정 파일 iot-servlet.xml에 추가

    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-mybatis.xml" />

최종 WebContent\WEB-INF\iot-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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">
 
 
	<!-- 컨트롤러 package 자동으로 스프링 컨테이너 등록 -->
	<context:component-scan base-package="com.iot.controller"/>
 
    <!-- ========================= JSP View Resolver ========================= -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- ========================= Import Definitions ========================= -->
	<import resource="iot-datasource.xml" />
	<import resource="iot-mybatis.xml" />
 
</beans>


댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
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
글 보관함