본문 바로가기
매일코딩/Spring

20.스프링프로젝트 - 스프링 마이바티스 mysql 연동

by 인생여희 2016. 11. 16.
반응형





1. mysql 테이블생성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
-- 데이터베이스 생성
CREATE DATABASE java;
 
 
-- 데이터 베이스 목록 확인
SHOW DATABASES;
 
 
 
--데이터베이스 선택
USE java;
 
-- 한줄 메모장 테이블
-- auto_increment 일련번호 증가
-- primary key :  기본키
-- varchar 가변사이즈 문자열
create table memo(
idx int not null auto_increment primary key,
writer varchar(50) not null,
memo varchar(1000) not null,
post_date datetime not null
);
cs



2pom.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
53
<repositories>
 
        <!-- ojdbc6.jar 다운로드를 위한 메이븐 저장소 추가 이 부분을 추가해야지 oracle메이븐을 내려 받을 수 있다. -->
        <repository>
            <id>codelds</id>
            <url>https://code.lds.org/nexus/content/groups/main-repo</url>
        </repository>
    </repositories>
 
 
 
    <!-- spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
 
        <!-- mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.31</version>
        </dependency>
 
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
 
        <!-- commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
 
        <!-- commons-lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
 
 
        <!-- 여기까지 -->
cs




3 root- context 작성


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
<?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:context="http://www.springframework.org/schema/context"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
 
    <!-- Root Context: defines shared resources visible to all other web components -->
 
    <!-- 아파치 DBCP 설정 DB 연결 설정 하기 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/java"/>
        <property name="username" value="아이디 " />
        <property name="password" value="비번" />
    </bean>
 
    <!-- "sqlSession 객체 주입 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 마이바티스 설정파일 - classpath는 src를말한다. -->
        <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
        <!-- 마이바티스 mapper파일 모음, 끝이 Mapper.xml로 끝나는 모든 파일을 읽어 들이겠다. -->
        <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
    </bean>
    <!-- SqlSession 객체 주입 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
        destroy-method="clearCache">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean>
</beans>
cs



4 src/main/resources 에 mybatis-config.xml 생성



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 
    <typeAliases>
 
        <!-- typeAlias type="전체경로" alias="별칭" -->
        <typeAlias type="org.co.nomad.model.dto"
            alias="memoDto" />
    
        
    </typeAliases>
 
</configuration>
 
 
cs



5 src/main/resources 에 mappers 패키지 만들고 memoMapper.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와 중복되지 않는 네임스페이스 기재 -->
<mapper namespace="memo">
 
 
    <select id="memoList" resultType="memoDto">
 
        select * from memo
        order by idx desc
 
    </select>
 
 
</mapper>
 
 
 
 
 
 
 
 
cs



여기까지가 설정 끝 이제 dto -> dao controller -> page 순으로 작성


6. 테스트 용이라 클래스명 대충 만들었다. ..변수명은 mysql 칼럼값과 일치 !


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
package org.co.nomad.model;
 
public class dto {
 
    
    
    private int idx;
    private String writer;
    private String memo;
    private String post_date;
    public int getIdx() {
        return idx;
    }
    public void setIdx(int idx) {
        this.idx = idx;
    }
    public String getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
    }
    public String getMemo() {
        return memo;
    }
    public void setMemo(String memo) {
        this.memo = memo;
    }
    public String getPost_date() {
        return post_date;
    }
    public void setPost_date(String post_date) {
        this.post_date = post_date;
    }
    @Override
    public String toString() {
        return "MemoDTO [idx=" + idx + ", writer=" + writer + ", memo=" + memo + ", post_date=" + post_date + "]";
    }
    
    public dto() {
        // TODO Auto-generated constructor stub
    }
    
    // idx와 날짜는 db에서 자동 입력이 된다.
    public dto(String writer, String memo) {
        super();
        this.writer = writer;
        this.memo = memo;
    }
    
    
}
 
cs



7 dao 와 daoimpl 생성


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
package org.co.nomad.model;
 
import java.util.List;
 
public interface dao {
 
    
    public List<dto> memoList();
    
}
 
 
 
====================================
 
 
package org.co.nomad.model;
 
import java.util.List;
 
import javax.inject.Inject;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
@Repository
public class daoimpl implements dao{
 
    @Inject // mybatis 실행 객체를 스프링에서 주입시킴
    SqlSession sqlSession;
    
    @Override
    public List<dto> memoList() {
        
        List<dto> list = null;
 
        try {
 
            list = sqlSession.selectList("memoList");
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return list;
    }
 
}
 
 
cs


8.컨트롤러 작성



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
package org.co.nomad.controller;
 
import javax.inject.Inject;
 
import org.co.nomad.model.dao;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class controller {
 
    @Inject
    dao dao;
 
    @RequestMapping("memo/memoList")
    public String memoList(Model model) {
 
        
        model.addAttribute("list", dao.memoList());
 
        return "home";
    }
 
}
 
cs



9.페이지에서 뿌리기


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <!-- 태그라이브러리 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
 
<P>  ${msg} </P>
 
 
 <h2>회원목록</h2>
 
    <table border="1">
        <tr>
            <th>아이디</th>
            <th>이름</th>
            <th>이메일</th>
            <th>회원가입일자</th>
 
        </tr>
        <c:forEach var="row" items="${list}">
            <tr>
                 <!-- 맴버 이름에 하이퍼링크 걸어서 누르면 수정삭제 상세 페이지로 이동하가ㅣ -->
                <td>${row.idx}</td>
                
                 <td>${row.writer}</td>
                <td>${row.memo}</td>
                <td>${row.post_date}</td>
            </tr>
        </c:forEach>
 
 
 
    </table>
 
</body>
</html>
 
cs




반응형

댓글