SPRING - Mybatis 사용하기(1)

이번엔 Mybatis 에 대해 알아보겠습니다

전에 JDBC template 를 사용해서

코드를 간결화 시켰었습니다 

Mybatis 를 사용 하면 훨씬더 간결하게 만들수 있고

JAVA 코드가 아닌 XML 코드를 사용하여 

데이터베이스에 접근합니다.


이번엔 포스팅에선 Mybatis 사용을 위한 준비를

먼저 하겠습니다. 먼저 db에 디벨로퍼로

테이블이랑 시퀀스 먼저 만들어줍니다.



위에서 테이블을 먼저 만든후 시퀀스 생성 하면됩니다.


다음 pom.xml 에서 Mybatis 

사용을 위해 의존 추가작업 을 해줍니다



다음 컨트롤러 보겠습니다


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
package com.spring.ex;
 
import java.text.DateFormat;
import java.util.ArrayList;
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.spring.ex.dao.ContentDao;
import com.spring.ex.dto.ContentDto;
 
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    ContentDao dao;
    
    @Autowired
    public void setDao(ContentDao dao) {
        this.dao = dao;
    }
    
    @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 "home";
    }
    
    @RequestMapping("/list")
    public String list(Model model) {
        ArrayList<ContentDto> dtos = dao.listDao();
        model.addAttribute("list", dtos);
        
        return "/list";
    }
    
    @RequestMapping("/writeForm")
    public String writeForm() {
        
        return "/writeForm";
    }
    
    @RequestMapping("/write")
    public String write(HttpServletRequest request, Model model) {
        dao.writeDao(request.getParameter("mWriter"), request.getParameter("mContent"));
        return "redirect:list";
    }
    
    @RequestMapping("/view")
    public String view() {
        
        return "/view";
    }
    
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request, Model model) {
        dao.deleteDao(request.getParameter("mId"));
        return "redirect:list";
    }
    
}
 
cs

29line에서 dao를 setter 해줍니다.

다음 47line 부터는 각 경로로 맵핑 시켜줍니다


다음 ContentDao 입니다


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
package com.spring.ex.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
 
import com.spring.ex.dto.ContentDto;
 
public class ContentDao implements IDao{
 
    JdbcTemplate template;
    
    @Autowired
    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }
    
    public ContentDao() {
    }
    
    @Override
    public ArrayList<ContentDto> listDao() {
        String query = "select * from board order by mId desc";
        ArrayList<ContentDto> dtos = (ArrayList<ContentDto>) template.query(query, new BeanPropertyRowMapper<ContentDto>(ContentDto.class));
        return dtos;
    }
    
    
    @Override
    public void writeDao(final String mWriter, final String mContent) {
        System.out.println("writeDao()");
        
        this.template.update(new PreparedStatementCreator() {
            
            @Override
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                String query = "insert into board (mId, mWriter, mContent) values (board_seq.nextval, ?, ?)";
                PreparedStatement pstmt = con.prepareStatement(query);
                pstmt.setString(1, mWriter);
                pstmt.setString(2, mContent);
                return pstmt;
            }
        });
        
    }
 
    
    @Override
    public ContentDto viewDao(String strID) {
        System.out.println("viewDao()");
        
        String query = "select * from board where mId = " + strID;
        return template.queryForObject(query, new BeanPropertyRowMapper<ContentDto>(ContentDto.class));
    }
 
    
    @Override
    public void deleteDao(final String bId) {
        System.out.println("deleteDao()");
        
        String query = "delete from board where mId = ?";
        this.template.update(query, new PreparedStatementSetter() {
            
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1, Integer.parseInt(bId));
            }
        });
        
    }
 
}
cs


18~23line JDBC template 선언하고 setter 해줍니다

29line 리스트를 출력하며 mId를 내림차순으로 order by합니다.


다음 글 내용보기 글삭제 글쓰기 기능 달아줍니다.


다음 servlet-context.xml 에서 빈생성 해줍니다



 다음 IDao.java 입니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.spring.ex.dao;
 
import java.util.ArrayList;
 
import com.spring.ex.dto.ContentDto;
 
public interface IDao {
    
    public ArrayList<ContentDto> listDao();
    public void writeDao(String mWriter, String mContent);
    public ContentDto viewDao(String strID);
    public void deleteDao(String bId);
    
}
cs


ContentDto.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.ex.dto;
 
public class ContentDto {
 
    private int mId;
    private String mWriter;
    private String mContent;
 
    public ContentDto() {
        
    }
    
    public ContentDto(int mId, String mWriter, String mContent) {
        this.mId = mId;
        this.mWriter = mWriter;
        this.mContent = mContent;
    }
 
    public int getmId() {
        return mId;
    }
 
    public void setmId(int mId) {
        this.mId = mId;
    }
 
    public String getmWriter() {
        return mWriter;
    }
 
    public void setmWriter(String mWriter) {
        this.mWriter = mWriter;
    }
 
    public String getmContent() {
        return mContent;
    }
 
    public void setmContent(String mContent) {
        this.mContent = mContent;
    }
 
}
 
cs

list.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
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="500" cellpadding="0" cellspacing="0" border="1">
    <tr>
        <td>번호</td>
        <td>작성자</td>
        <td>내용</td>
        <td>삭제</td>
    <tr>
    <c:forEach items="${list}" var="dto">
    <tr>
        <td>${dto.mId}</td>
        <td>${dto.mWriter}</td>
        <td>${dto.mContent}</td>
        <td><a href="delete?mId=${dto.mId}">X</a></td>
    <tr>
    </c:forEach>
</table>
<p><a href="writeForm">글작성</a></p>
</body>
</html>
cs

view.jsp


1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
list.jsp
</body>
</html>
cs



writeForm.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
write.jsp <br />
 
<table width="500" cellpadding="0" cellspacing="0" border="1">
        <form action="write" method="post">
            <tr>
                <td > 작성자 </td>
                <td> <input type="text" name="mWriter" size = "50"> </td>
            </tr>
            <tr>
                <td> 내용 </td>
                <td> <input type="text" name="mContent" size = "150" > </td>
            </tr>
            <tr >
                <td colspan="2"> <input type="submit" value="입력">    <a href="list">목록보기</a></td>
            </tr>
        </form>
</table>
</body>
</html>
cs


'SPRING' 카테고리의 다른 글

SPRING - Mybatis 사용하기(3)  (0) 2018.02.13
SPRING - Mybatis 사용하기(2)  (0) 2018.02.13
SPRING - 스프링 트랜잭션(3)  (0) 2018.02.08
SPRING - 스프링 트랜잭션(2)  (0) 2018.02.08
SPRING - 스프링 트랜잭션(1)  (0) 2018.02.08

댓글

Designed by JB FACTORY