상세 컨텐츠

본문 제목

[Spring MVC project] mybatis(마이바티스) DB(데이터베이스)연동 1

Spring

by kwanghyup 2019. 11. 3. 20:00

본문

개요 

데이터 베이스 구성

  - 테이블명 : test , 컬럼 : id, pw   

 

Step1 : 프로젝트생성 및  pom.xml 파일 설정

Step2: root-context.xml 설정    

Step3 : com.dbtest.dao

  - Interface : Mapper.java

  - class : Test.java

Step4  : Mapper.xml  

Step5 : Homecontroller.java  

Step6: index.jsp list.jsp

 

시작

 

Spring MVC project 다음과 같이 생성

  - 프로젝트명 : dbTest 

  - 패키지 : com.dbtest.controller

 

Step1 : pom.xml 파일 수정 및 Dependency 추가

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.kwanghyup</groupId>
	<artifactId>test</artifactId>
	<name>dbTest</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version> 
		<org.springframework-version>4.3.4.RELEASE </org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId> 
			<version>3.0.1</version> 
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId> 
			<artifactId>jsp-api</artifactId> 
			<version>2.2</version> 
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId> 
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version> 
			<scope>test</scope>
		</dependency>

		<!-- mysql 추가-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.48</version>
		</dependency>
		
        <!-- mybatis 추가-->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.1</version>
		</dependency>
		
        <!-- mabatis-spring 추가-->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.1</version>
		</dependency>
		
        <!-- spring-jdbc 추가 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
        <!-- spring-test 추가 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
			<scope>test</scope>
		</dependency>
        
	</dependencies>
	
    <build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>
                        	org.springframework.ide.eclipse.core.springnature
                        </projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>
                        	org.springframework.ide.eclipse.core.springbuilder
                        </buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source> 
					<target>1.8</target> 
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

[프로젝트명]우클릭 - [Properties] - [Project Facets] 

  - Dynamic web Module 3.1로 변경

  - java 1.8로 변경 

 

 Step2 : src/main/webapp/WEB-INF/spring/root-context.xml 설정 

[ Namespace ] - aop, mybatis 체크

<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
	
	 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
	    <property name="url" value="jdbc:mysql://localhost:3306/kwanghyup?useSSL=false"></property>
	    <property name="username" value="root"></property>
	    <property name="password" value="1234"></property>
	</bean>
	 
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"/>
    	<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
	</bean>
    
    <mybatis-spring:scan base-package="com.dbtest.dao"/>

</beans>    

 

Step3 

 package : com.dbtest.dao 

  - Interface : Mapper.java

  - class : Test.java

 

Mapper.java

package com.dbtest.dao;

import org.apache.ibatis.annotations.Param;

// 인터페이스를 통해 DB에 접근 
public interface Mapper {
	public String memberId(@Param("memberId") String memberId); 
}

 

Test.java

package com.dbtest.dao;

public class Test {
	private String memberId;
	private String memberPw;
	public String getMemberId() {
		return memberId;
	}
	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}
	public String getMemberPw() {
		return memberPw;
	}
	public void setMemberPw(String memberPw) {
		this.memberPw = memberPw;
	}
	@Override
	public String toString() {
		return "Test [memberId=" + memberId + ", memberPw=" + memberPw + "]";
	}
}

 

Step4 

 - src/main/resource 아래 mapper 폴더 생성

 - src/main/resource 아래 Mapper.xml  파일 생성 

 

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.dbtest.dao.Mapper">
  <select id="memberId" resultType="String">
    select pw from test where id = #{memberId}
  </select>
</mapper>

데이터 베이스 구성

  - 테이블명 : test , 컬럼 : id, pw   

 

Step5 : com.dbtest.controller.Homcontroller.java 수정

 

Homcontroller.java

package com.dbtest.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dbtest.dao.Mapper;

@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	public Mapper mapper;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "index";
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public String list(HttpServletRequest request, Model model) {
		
		String memberId = request.getParameter("memberId"); 
		model.addAttribute("memberId", mapper.memberId(memberId));
		return "list";
	}
	
}

 

Step6 : index.jsp , list.jsp 파일 생성

 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%String context = request.getContextPath(); %>
<form action="<%=context%>/list" method="post">
	<input type="text" name="memberId">
	<input type="submit" value="test">
</form>
</body>
</html>

 

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${memberId}
</body>
</html>

 

[프로젝트명] 우클릭 -  Run on Server 

 

데이터베이스에 저장된 id 입력 - test버튼 클릭 -  입력한  id에 대응되는 비밀번호가 출력되면 성공

 

관련글 더보기

댓글 영역