상세 컨텐츠

본문 제목

Spring - MyBatis, Annotation을 활용하여 db 불러오기 예제

Archive

by 에스프리터 2018. 4. 6. 17:54

본문






늘은 Spring을 활용하여 웹에서 SQL DB를 출력하고 검색해보는 예제입니다. 내용은 예전과 크게 다를 게 없지만 차이가 있면 Spring 기반에서 MyBatis를 활용하여 db를 불러온다는.. 즉, 구조가 약간 다릅니다.

파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.




pack.controller 패키지

** ListController.java **
package pack.controller;

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 pack.model.SangpumInter;

@Controller
public class ListController {
    @Autowired
    private SangpumInter inter;
    
    @RequestMapping("list")
    public String process(Model model) {
        model.addAttribute("data", inter.list());
        return "sanglist";
    }
}





** SangpumBean.java **
package pack.controller;

public class SangpumBean {
    //추가, 수정 작업이 있다면 code,sang,su,dan 작업
    
    //상품 검색용
    private String searchValue;
    
    public String getSearchValue() {
        return searchValue;
    }
    
    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }
}


** SearchController.java **
package pack.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import pack.model.SangpumDto;
import pack.model.SangpumInter;

@Controller
public class SearchController {
    @Autowired
    private SangpumInter inter;
    
    @RequestMapping(value="search", method=RequestMethod.POST)
    public ModelAndView searchProcess(SangpumBean bean) {
        List<SangpumDto> list = inter.search(bean);
        return new ModelAndView("sanglist", "data", list);
    }
}



pack.model 패키지

** SangpumAnnoInter.java **
package pack.model;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import pack.controller.SangpumBean;

public interface SangpumAnnoInter {
    //MyBatis SQL mapping interface
    @Select("select * from sangdata")
    public List<SangpumDto> selectAll();
    
    @Select("select * from sangdata where sang like concat('%',#{searchValue},'%')")
    public List<SangpumDto> selectSearch(SangpumBean bean);
}


** SangpumDto.java **
package pack.model;

public class SangpumDto {
    private String code, sang;
    private int su, dan;
    
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getSang() {
        return sang;
    }
    public void setSang(String sang) {
        this.sang = sang;
    }
    public int getSu() {
        return su;
    }
    public void setSu(int su) {
        this.su = su;
    }
    public int getDan() {
        return dan;
    }
    public void setDan(int dan) {
        this.dan = dan;
    }
}


** SangpumImpl.java **
package pack.model;

import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import pack.controller.SangpumBean;

@Repository
public class SangpumImpl implements SangpumInter{
    @Autowired
    private SangpumAnnoInter sangpumAnnoInter;
    
    public List<SangpumDto> list() throws DataAccessException {
        return sangpumAnnoInter.selectAll();
    }
    
    public List<SangpumDto> search(SangpumBean bean) throws DataAccessException {
        return sangpumAnnoInter.selectSearch(bean);
    }
}





** SangpumInter.java **
package pack.model;

import java.util.List;
import org.springframework.dao.DataAccessException;
import pack.controller.SangpumBean;

public interface SangpumInter {
    List<SangpumDto> list() throws DataAccessException;
    List<SangpumDto> search(SangpumBean bean) throws DataAccessException;
}


pack.resource 폴더

** db.properties(예제입니다 / 각자의 환경에 맞게 고치세요) **
driver=org.mariadb.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=123

src 폴더

** sanglist.html **
<%@ 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>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
* 상품 자료(@MVC - MyBatis Anno) * <p/>
<table border="1">
  <tr><th>code</th><th>sang</th><th>su</th><th>dan</th></tr>
  <c:forEach var="s" items="${data}">
  <tr>
      <td>${s.code }</td>
      <td>${s.sang }</td>
      <td>${s.su }</td>
      <td>${s.dan }</td>
  </tr>
  </c:forEach>
  <!-- 검색 -->
  <tr>
      <td colspan="4">
          <form action="search" method="post">
          상품명:<input type="text" name="searchValue">
          <input type="submit" value="검색">
          </form>
      </td>
  </tr>
</table>
</body>
</html>

** mvc-config.xml **
<?xml version="1.0" encoding="UTF-8"?>


    <context:component-scan
            base-package="pack.controller"/>
    <context:component-scan
            base-package="pack.model"/>        

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>


** web.xml **
<?xml version="1.0" encoding="ISO-8859-1"?>
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         id="WebApp_ID" version="2.5">

    <display-name>sweb16_mybatis_anno</display-name>
    
   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <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>


** index.jsp **
<!DOCTYPE html>

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

<html>
<head>
    <meta charset="utf-8">
    <title>Welcome</title>
</head>
<body>
    <a href="list">Click to enter</a>
</body>
</html>


그 외

** pom.xml **
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples.service.service</groupId>
  <artifactId>sweb16_mybatis_anno</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <properties>
      <!-- Generic properties -->
      <java.version>1.8</java.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      
      <!-- Web -->
      <jsp.version>2.2</jsp.version>
      <jstl.version>1.2</jstl.version>
      <servlet.version>2.5</servlet.version>

      <!-- Spring -->
      <spring-framework.version>4.3.11.RELEASE</spring-framework.version>

      <!-- Logging -->
      <logback.version>1.0.13</logback.version>
      <slf4j.version>1.7.5</slf4j.version>
   </properties>
   
   <dependencies>
      <!-- Spring MVC -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>${spring-framework.version}</version>
      </dependency>
      
      <!-- Other Web dependencies -->
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>${jstl.version}</version>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>servlet-api</artifactId>
         <version>${servlet.version}</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>javax.servlet.jsp</groupId>
         <artifactId>jsp-api</artifactId>
         <version>${jsp.version}</version>
         <scope>provided</scope>
      </dependency>
   
      <!-- Spring and Transactions -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-tx</artifactId>
         <version>${spring-framework.version}</version>
      </dependency>

      <!-- Logging with SLF4J & LogBack -->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>${slf4j.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>ch.qos.logback</groupId>
         <artifactId>logback-classic</artifactId>
         <version>${logback.version}</version>
         <scope>runtime</scope>
      </dependency>
      
          <!-- RDBMS : MariaDb driver -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.2.3</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>  
    
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    
    
        <!-- Mybatis -->
        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
        </dependency>

        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
        </dependency>
      
   </dependencies>   
</project>
    




결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.








태그

관련글 더보기

댓글 영역