본문 바로가기
IT/MyBatis

[MyBatis] DB 연결

by dya0 2019. 6. 17.

Member.java

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package model;
 
public class Member {
    private String id;
    private String password;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
 

Member.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
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8" ?>
<!-- SQL 맵퍼 파일은 XML 이기 때문에 제일먼저 xml 선언이 온다. -->
<!-- 태그 규칙을 정의한 DTD 선언 -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<!-- namespace로 별칭 구분  -->
<!-- SQL 맵퍼 파일은 루트 엘리먼트 <mapper>를 작성하는 거승로 시작한다.
프로젝트에서는 기본적으로 여러개의 <mapper>를 가지기 때문에 중복되는 이름을 가진 SQL문이 존재할 수 있다.
따라서 각 <mapper> 마다 namespace 속성을 이용하여 <mapper>를 구분한다.
 -->
<mapper namespace="Member1">
 
<!-- resultType의 member는 sqlMapConfig안의 alias로 선언한 model.Member이다. -->
<select id = "select" parameterType="String" resultType="Member">
select * from member22 where id =#{inputid}
</select>
<!-- 
<select id = "list" resultType="Member">
id 속성 : SQL문을 작성할 때 각각의 SQL 문을 구분하기 위해 id 속성을 사용한다.
resultType 속성 : select 문의 실행 결과를 담을 객체를 지정한다.
    - 마이바티스는 select 결과를 저장하고자 resultType에 선언도니 클래스의 인스턴스를 생성한다.
    그리고 각 칼럼에 대응하는 setter 메서드를 찾아서 호출한다.
    이때 setter 메서드는 대소문자 구분 없이 set을 뺀 메서드의 이름과 컬럼 이름이 같으면 된다.
    - 컬럼의 이름과 일치하는 setter가 없다면 해당 컬럼의 값은 인스턴스에 저장되지 않는다.
 
 -->
 
<insert id = "insert" parameterType="Member">
insert into member22 values (#{id}, #{password})
</insert>
<!-- select 태그에는 select SQL 문을 사용한다. -->
<select id = "list" resultType="Member">
select * from member22
</select>
<!-- 
1. 마이바티스의 입력 매개 변수를 #{프로퍼티명}으로 표시한다.
parameterType="String" : 
parameterType은 DAO(MemberDAO)에서 
session.selectOne("select",id); 문장의 두 번째 매개변수의 자료형이다.
#{inputid} : id의 값을 사용하기 위해 어떤 이름을 사용해도 무방하다.
=>매개변수의 자료형이 기본형이나 String 인 경우 어떤 이름을 사용해도 상관 없다.
 
2. resultType 속성 : select 문의 실행 결과를 다음 객체로 지정한다.
parameterType = "Member"인 경우 
#{id} : Member객체의 프로퍼티 값이 적용된다. 
public String getId(){
return id;}
의 반환 값이 적용된다.
 
#{password}는 Member객체의 프로퍼티 값이 적용된다. 
즉, model/Member.java의 
public String getPassword(){
return password;
}의 반환값이 적용된다. 
 -->
 
 
</mapper>
 
 

sqlMapConfig.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
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
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 이 파일은 mybatis 설정 파일로 xml이기 때문에 제일 먼저 xml 선언이 들어온다. -->
<!-- XML 기술을 사용하여 작성하기 때문에 제일 먼저 XML 선언과 태그 규칙을 정의한 DTD선언이 온다.
DTD란 문서 평식 정의 Document Type Definition, DTD라는 컴퓨터 용어로 SGML을 비록해 HTML, XHTML, XML등에서 쓰입니다.  -->
<!-- 태그 규칙을 정의한 DTD 선언이 옵니다. 
getter setter 로 담아옴 -->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
<!-- mybatis 설정 파일의 루트 엘리먼트이다. -->
<configuration>    
<!-- typeAliases 엘리먼트 : 자바 클래스 이름(패키지 이름 포함)에 대한 별명을 설정하는데 
SQL맵퍼 파일에서 사용할 별명들이다. 
1. typeAlias 태그의 type 속성 값은 패키지 이름을 포함한 클래스 이름이다. 
2. typeAlias태그의 alias 속성은 type에서 지정한 클래스의 별명이다. 
3. Member.xml에서 <insert id = "insert" parameterType = "Member">
parameterType = "Member"에서 사용되고 있다.
 -->
    <typeAliases> <!-- 길기때문에 별칭을 사용하겠다 -->
        <typeAlias type = "model.Member" alias = "Member"/>
    </typeAliases>
    <!-- <environments> 엘리먼트: 
        프레임워크에서 사용할 DB정보 (트랜잭션 관리자, 데이터 소스)를 설정한다.
        이 태그를 이용하면 여러개의 데이터 베이스 접속 정보를 설정할 수 있다. 
        설정도니 정보 중에서 하나를 선택할 때 default속성을 사용한다.
        <environment> 엘리먼트 : 각각의 데이터베이스 접속 정보를 정의한다.
        id 속성은 <environment>를 구분할 때 사용할 식별자이다.
        <transactionManager> 엘리먼트 
        트랜잭션 관리 유형 두가지 - type에서 설정한다.
        1. JDBC : 직접 JDBC의 commit, rollback 기능을 사용하여 mybatis자체에서 트랜잭션을 관리합니다.
        2. MANAGED : JAVA EE 애플리케이션 서버 (JBoss, WebLogic, WepSphere)나 
        서블릿 컨테이너(톰캣 서버)에서 트랜잭션을 관리한다.
        <dataSource> 엘리먼트
        mybatis는 JDBC 표준 인터페이스인 javax.sql.DataSource 구현체를 이용하여 DB커넥션을 다룬다.
        
        사용 가능한 세가지 유형 
        1. UNPOOLED : DB 커넥션을 요청할 때마다 매번 커넥션 객체를 생성한다. 
        높은 성능을 요구하지 않는 단순한 애플리케이션에 적합하다.
        2. POOLED: 미리 DB 커넥션 객체를 생성해두고 요청하면 즉시 반환한다.
        데이터베이스에 연결하느 과정, 즉 연결을 초기화하고 사용자를 인증하는 과정이 없기 때문에 속도가 빠르다.
        3. JNDI : JAVA EE 애플리케이션 서버나 서블릿 컨테이너(예 : 톰캣 서버)에서 제공하는 
        데이터 소스 (dataSource)를 사용한다.
        
        ==
        내가 실행할 맵퍼파일
    -->
        <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            <property name="driver"
                      value="oracle.jdbc.driver.OracleDriver"/>
            <property name="url" value="jdbc:oracle:thin:localhost:1521:xe"/>
            <property name="username" value="scott"/>
            <property name="password" value="tiger"/>
            </dataSource>
        </environment>
    </environments>
        <!-- <mappers> 엘리먼트 : SQL 맵퍼 파일들의 정보를 설정할 때 사용한다. 
        각각의 SQL 맵퍼 파일의 정보는 <mapper>태그로 정의한다. 
        SQL 맴퍼 팡리의 경로르 설정할 때 두가지 방법이 있다. 
        1. 자바의 클래스 경로를 사용하는 방법 : resource속성을 사용한다.
        2. 파일 시스템 경로르 ㄹ사용하는 방법 : url 속성을 사용하낟.
            예) c:/model 폴더에 Member.xml 에 있는 경우 
            <mapper url="file:///c:/model/Member.xml" /> -->
        <mappers>
        <!-- <mapper url="file:///D:/oxygen/MyBatis1/src/Member.xml /> -->
        <mapper resource="Member.xml"/>
    </mappers>
</configuration>

 

 
 

MemberDao.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package dao;
 
 
 
 
public class MemberDao {
    private SqlSession getSession() {
        SqlSession session = null;
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("sqlMapConfig.xml");
            SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(reader);
            session = sf.openSession(true);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return session;
    }
 
    public int chk(Member member) {
        int result = 0// id가 없는 경우
        SqlSession session = null;
        try {
            session = getSession();
            // selectOne 결과가 없는 경우 mem 은 null namespace Member1
            Member mem = (Member) session.selectOne("Member1.select"member.getId());
            // object 형이니까 반드시 캐스팅
            // 채우기
            if (mem != null) {
 
                if (mem.getId().equals(member.getId())) {
                    result = -1;
                    if (mem.getPassword().equals(member.getPassword())) {
                        result = 1;
                    }
                }
            } else {
                System.out.println("chk()결과가 null");
            }
            // 여려개면 map으로 넘겨서 사용
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return result;
    }
 
    public int insert(Member member) {
        int result = 0;
        SqlSession session = null;
        try {
            session = getSession();
            result = session.insert("Member1.insert", member);
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return result;
    }
 
}
 

 

index.jsp

1
2
3
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:forward page ="/main.net"/>

 

main.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style>
div {
    background: green;
    color: white;
    text-align: right;
}
</style>
</head>
<body>
<c:if test= '${empty sessionScope.id }'>
<script>
location.href="login.net";
</script>
</c:if>
<h2>로그인 되었습니다.</h2> <a href="Logout.net">로그아웃</a>
<hr>
<c:if test = "${sessionScope.id=='admin' }">
    <c:out value = "관리자 모드!"/><br>
    <a href="List.net">회원 명단</a>
</c:if>
</body>
</html>

login.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
 
<head>
<meta charset="EUC-KR">
<script
<link rel="stylesheet" type="text/css" href="../ch03-2.css">
<title>로그인 입력</title>
<style>
body {
    font-family: Arial, Helvetica, sans-serif;
}
 
{
    box-sizing: border-box
}
 
input[type=text], input[type=password] {
    width: 100%;
    padding: 15px;
    margin: 5px 0 22px 0;
    display: inline-block;
    border: none;
    background: #f1f1f1;
}
 
input[type=text]:focus, input[type=password]:focus {
    background-color: #ddd;
    outline: none;
}
 
button {
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer; /* 손가락 커서 모양 */
    width: 100%;
    opacity: 0.9;
}
 
button:hover {
    opacity: 1;
}
 
button:focus {
    outline: none;
}
 
/* 취소 버튼*/
.join {
    padding: 14px 20px;
    background-color: #f44336;
}
 
.join, .submitbtn {
    float: left;
    width: 50%;
}
 
form {
    background-color: #fefefe;
    margin: 5% auto 15% auto;
    /* 5% from the top, 15% from the bottom and centered */
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
    padding: 16px;
}
 
hr {
    border: 1px solid #f1f1f1;
    margin-bottom: 25px;
}
/* Clear floats */
.clearfix::after {
    content: "";
    clear: both;
    display: table;
}
 
/* Change styles for cancel button and signup button on extra small screens */
@media screen and (max-width: 300px) {
    .join, .signupbtn {
        width: 100%;
    }
}
</style>
<script>
    $(function() {
        $(".join").click(function() {
            location.href = "join.net";
        });
    })
</script>
</head>
<body>
    <form action="loginPro.net" method="POST" name="loginform">
        <h1>로그인</h1>
        <hr>
        <b>아이디</b> <input type="text" name="id" placeholder="Enter id"
            required> <b>비밀번호</b> <input type="text" name="password"
            placeholder="Enter password" required>
 
        <div class="clearfix">
            <button type="submit" class="submitbtn">Submit</button>
            <button type="button" class="join">회원가입</button>
        </div>
    </form>
</body>
</html>

 

join.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
36
37
38
39
40
41
42
43
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<%--jsp:useBean id="myform" class="javaBean.Testforsend"/ --%>
<!DOCTYPE html>
<html>
<head>
<title>회원가입</title>
<link rel="stylesheet" href="css/join.css">
<!--autoload=false 파라미터를 이용하여 자동으로 로딩되는 것을 막습니다.-->
 
<style>
{
    width: 100%;
    display: block
}
 
input[name=id], input[name=email] {
    width: 60%
}
 
#message, #email_message {
    width: 35%;
    display: inline-block
}
</style>
 
</head>
<body>
    <form name="joinform" action="joinPro.net" method="post">
        <h1>회원가입</h1>
        <hr>
        <b>아이디</b><input type="text" name="id" placeholder="Enter id" required>
        <span id="message"></span> <b>비밀번호</b><input type="text"
            name="password" placeholder="Enter password" required> <b>이름</b>
        <div class="clearfix">
            <button type="submit" class="submitbtn">회원가입</button>
            <button type="reset" class="cancelbtn">다시작성</button>
        </div>
    </form>
 
</body>
</html>

'IT > MyBatis' 카테고리의 다른 글

[MyBatis] 조인  (1) 2019.06.20
[MyBatis]  (0) 2019.06.19
[MyBatis] 마이바티스 날짜 조건으로 조회  (1) 2019.06.19
[MyBatis]  (0) 2019.06.17