상세 컨텐츠

본문 제목

3탄. MyBatis 설정

Spring

by husks 2014. 3. 10. 16:24

본문

반응형

- http://huskdoll.tistory.com/8 (1탄. gradle 로 이클립스 MVC 프로젝트 생성)

- http://huskdoll.tistory.com/9 (2탄. Spring xml 설정을 java설정으로 변경 (Spring JavaConfig))

위의 단계를 완료한 후에 설정 하시면 됩니다.

MyBatis 설정을 하기위한 소스 예제를 작성 하였습니다.

아래에 디렉토리를 참고하셔서 순서대로 따라해 보시길 바랍니다. ^^

소스는 https://github.com/psyken/SpringGradle 에 올려 놓았습니다.




 ※디렉토리 참고

- 파란색 (수정)
- 빨간색 (추가)
























1. 조회 할 Table 및 데이터 입력

1.1 테이블 생성
1
2
3
4
5
6
7
8
9
10
CREATE TABLE BOOKS (
  ID VARCHAR(5NOT NULL,
  NAME VARCHAR(20NOT NULL,
  WRITER VARCHAR(20NOT NULL,
  PRICE DECIMAL(10,2DEFAULT 0,
  GENRE VARCHAR(20NOT NULL,
  PUBLISHER VARCHAR(20NOT NULL,
  CNT DECIMAL(10,0DEFAULT 0,
  PRIMARY KEY  (ID)
ENGINE=InnoDB DEFAULT CHARSET=utf8

1.2 데이터 입력
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
32
33
34
35
INSERT INTO BOOKS(
  ID,
  NAME,
  WRITER,
  PRICE,
  GENRE,
  PUBLISHER
VALUES (
  'A1',
  '홍길동전',
  '허균',
  300,
  '소설',
  '허균 출판사'
)
 ON DUPLICATE KEY UPDATE
 CNT = CNT+1;
 
 INSERT INTO BOOKS(
  ID,
  NAME,
  WRITER,
  PRICE,
  GENRE,
  PUBLISHER
VALUES (
  'B1',
  '레미제라블',
  '빅토르 위고',
  900,
  '소설',
  '빅토르 위고 출판사'
)
 ON DUPLICATE KEY UPDATE
 CNT = CNT+1;


2. build.gradle 내용 수정

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'psyken' at '14. 3. 5 오후 3:46' with Gradle 1.11
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at http://gradle.org/docs/1.11/userguide/tutorial_java_projects.html
 */
 
// Apply the java plugin to add support for Java
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'
 
// JAVA Version 1.6
sourceCompatibility = 1.6
// 개발한 애플리케이션 버전
version = '1.0'
 
// 메이븐 Central 저장소 사용
repositories {
    mavenCentral()
}
 
// dependency 버전 정보
def version = [
spring: '3.2.2.RELEASE'
, junit: '4.11'
, servletApi: '3.0.1'
, jstl: '1.2'
, slf4j: '1.7.6'
, mockito: '1.9.0'
, cglib: '2.2.2'
, logback: '1.0.6'
, mybatis: '3.2.2' //MyBatis 추가
, mybatisSpring: '1.2.0' //MyBatis 추가
, mysql: '5.1.26' //MyBatis 추가
]
 
// In this section you declare the dependencies for your production and test code
// 의존성 설정
dependencies {
    compile "org.springframework:spring-webmvc:${version.spring}",
          "cglib:cglib-nodep:${version.cglib}",
          "ch.qos.logback:logback-classic:${version.logback}",
          "org.slf4j:slf4j-api:${version.slf4j}",
          "org.mybatis:mybatis:${version.mybatis}"//MyBatis 추가
          "org.mybatis:mybatis-spring:${version.mybatisSpring}"//MyBatis 추가
          "mysql:mysql-connector-java:${version.mysql}"//MyBatis 추가
          "org.springframework:spring-jdbc:${version.spring}"//MyBatis 추가
          "org.springframework:spring-tx:${version.spring}" //MyBatis 추가
 
  providedCompile "javax.servlet:javax.servlet-api:${version.servletApi}"
 
  testCompile "org.springframework:spring-test:${version.spring}",
              "junit:junit:${version.junit}",
              "org.mockito:mockito-core:${version.mockito}"
                                        
  runtime "javax.servlet:jstl:${version.jstl}"
}
 
// logback(slf4j)를 사용하기 때문에 모든 의존성에서 commons-logging는 제외
[configurations.runtime, configurations.default]*.exclude(module: 'commons-logging')
 
// JAVA 컴파일시 인코딩 설정
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
 
// TEST 설정
test {
    jvmArgs = ['-ea''-Xmx256m']
    logging.captureStandardOutput(LogLevel.INFO)
    testReport = false
}
 
// 프로젝트 초기화
// 1. java source directory 생성 : src/main/java, src/test/java
// 2. resource directory 생성    : src/main/resource, src/test/resource
// 3. web source directory 생성  : src/main/webapp, src/main/webapp/WEB-INF
task initProject(description: 'initialize project'<< {
    createDir = {
        println "create source directory: $it"
        it.mkdirs()
    }
    sourceSets*.java.srcDirs*.each createDir
    sourceSets*.resources.srcDirs*.each createDir
    createDir webAppDir
    createDir new File(webAppDir, '/WEB-INF')
}

36 ~ 38 라인 추가

48 ~ 52 라인 추가


3. ModuleConfig.java 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.spring.www.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
 
/**
 * 웹쪽 설정이 아닌 공통으로 쓰일수 있는 부분의 설정
 */
@Configuration
@ImportResource("classpath:mybatis/context-mybatis.xml")
public class ModuleConfig {
 
}


4. WebInitializer.java 내용 수정

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
32
33
34
35
package com.spring.www.config;
 
import javax.servlet.Filter;
 
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
     
  @Override
  protected Class<?>[] getRootConfigClasses() {
      return new Class<?>[]{ ModuleConfig.class };//ModuleConfig 웹쪽 설정이 아닌 공통으로 쓰일수 있는 부분의 설정
      //return null; //주석처리
  }
 
  @Override
  protected Class<?>[] getServletConfigClasses() {
      return new Class<?>[] { WebConfig.class };
  }
 
  @Override
  protected String[] getServletMappings() {
      return new String[] { "/" };
  }
 
  @Override
  protected Filter[] getServletFilters() {
 
      CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
      characterEncodingFilter.setEncoding("UTF-8");
      
      return new Filter[] { characterEncodingFilter};
      
  }
}
12 라인 추가


5. db.properties 생성

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/db
jdbc.user=username
jdbc.pwd=password 



6. context-mybatis.xml 생성
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?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:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 
 <context:component-scan base-package="com.spring.www" />
 
 <context:property-placeholder location="classpath:mybatis/db.properties"/>
 
 <!-- commons dbcp : 커넥션 풀 사용 (commons-dbcp을 pom.xml에 dependencies 한다.)--> 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
  <property name="driverClassName" value="${jdbc.driver}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.user}"/>
  <property name="password" value="${jdbc.pwd}"/>
  
  <property name="maxActive" value="50"/>
  <property name="maxIdle" value="30"/>
  <property name="minIdle" value="30"/>
  <property name="maxWait" value="5"/>
  
 </bean>
 
 <!-- MyBatis 맵퍼의 SQL 문장에 대한 파라미터 및 리턴 타입을 담을 클래스를 검색 할 패키지 지정 -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />        
  <property name="mapperLocations" value="classpath:mybatis/sqlmaps/*.xml" />
 </bean>
 
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
 </bean>
 
 <!-- 맵퍼 인터페이스와 맵퍼 XML 파일에 의해 생성되는 맵퍼 클래스를 빈에 주입 할 수 있도록 설정 -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
   <property name="basePackage" value="com.spring.www" />
 </bean>
  
 <!-- 트랜잭션 관리자. id가 transactionManager이면, 아래 tx:annotation-driven에서 transactionManager 속성을 지정할 필요 없음 -->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
 </bean>
 
 <!-- 애노테이션으로 트랜잭션 설정 할 수 있도록 -->
 <tx:annotation-driven />
 <!--tx:annotation-driven transaction-manager="transactionManager" /-->
 
</beans>


7. Domain 생성 (Book.java)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.spring.www.domain;
 
public class Book {
    
    private String id;
    private String name;
    private String writer;
    private String price;
    private String genre;
    private String publisher;
    private String cnt;
    
    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 getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getGenre() {
        return genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
    public String getCnt() {
        return cnt;
    }
    public void setCnt(String cnt) {
        this.cnt = cnt;
    }
    
}


8. Dao 생성 (DataBookDao.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.spring.www.dao;
 
import java.util.List;
 
import com.spring.www.domain.Book;
 
public interface DataBookDao {
 
    List<Book> selectAllBook();
    
    String selectBookName(String id);
 
}


9. DaoImpl 생성 (DataBookDaoImpl.java)

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
32
33
34
35
36
37
38
package com.spring.www.daoImpl;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.spring.www.dao.DataBookDao;
import com.spring.www.domain.Book;
 
@Repository("DataBookDao")
public class DataBookDaoImpl implements DataBookDao{
 
    @Autowired
    private SqlSession sqlSession;
 
    public void setSqlSession(SqlSession sqlSession){
        this.sqlSession = sqlSession;
    }
 
    @Override
    public List<Book> selectAllBook() {
        // TODO Auto-generated method stub
        List<Book> users = sqlSession.selectList("getBookInfo");
 
        return users;
    }
 
    @Override
    public String selectBookName(String id) {
        // TODO Auto-generated method stub
        String name = sqlSession.selectOne("getBookName", id);
 
        return name;
    }
 
}


10. 쿼리 xml 생성 (book.xml)

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
<?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.spring.www.dao.DataBookDao"><!-- namespace에서 interface로 정의된 DAO를 정확히 명시해주어야 한다 -->
  <select id="getBookInfo" resultType="com.spring.www.domain.Book">
    SELECT
      ID,
      NAME,
      WRITER,
      PRICE,
      GENRE,
      PUBLISHER,
      CNT 
    FROM
      BOOKS
  </select>
  <select id="getBookName" parameterType="string" resultType="string">
    SELECT
      NAME
    FROM
      BOOKS
    WHERE
      ID = #{id}
  </select>
</mapper>


11. controller 생성 (HomeController.java)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.spring.www.controller;
 
import javax.annotation.Resource;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import com.spring.www.dao.DataBookDao;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
 
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
 
    @Resource(name="DataBookDao")
    private DataBookDao bookDao;
 
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Model model) {
 
        model.addAttribute("books", bookDao.selectAllBook());        
 
        return "books";
 
    }
 
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String home(@PathVariable("id"String id, Model model) {
 
        model.addAttribute("bookName", bookDao.selectBookName(id));        
 
        return "book";
 
    }
 
}


12. view 생성 [단건 출력] (book.jsp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page session="false" %>
<html>
<head>
  <title>Home</title>
</head>
<body>
<h1>
  Book Name.
</h1>
 
<P>  This book's name is [${bookName}]. </P>
</body>
</html>


13. view 생성 [리스트 출력] (books.jsp)

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
32
33
34
35
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page session="false" %>
<html>
<head>
  <title>Home</title>
</head>
<body>
<h1>
  Book List.
</h1>
<table border="1">
  <tr align="center">
    <td width="100px">아이디</td>
    <td width="100px">이름</td>
    <td width="100px">작가</td>
    <td width="100px">가격</td>
    <td width="100px">장르</td>
    <td width="100px">출판사</td>
    <td width="100px">수량</td>
  </tr>
<c:forEach var="book" items="${books}">
  <tr align="center">
    <td width="100px">${book.id}</td>
    <td width="100px">${book.name}</td>
    <td width="100px">${book.writer}</td>
    <td width="100px">${book.price}</td>
    <td width="100px">${book.genre}</td>
    <td width="100px">${book.publisher}</td>
    <td width="100px">${book.cnt}</td>
  </tr>
</c:forEach>
</table>
</body>
</html>



14. 페이지 호출

URL 창에 http://localhost:8080/ 입력 하시면 전체 책 목록이 나옵니다.

http://localhost:8080/책아이디 를 입력하시면 해당 아이디의 책 이름이 보이게 됩니다.





반응형

관련글 더보기

댓글 영역