BOARD.sql
xxxxxxxxxx
CREATE TABLE BOARD(
SEQ int PRIMARY KEY,
TITLE VARCHAR(200),
WRITER VARCHAR(20),
CONTENT VARCHAR(2000),
REGDATE datetime DEFAULT current_timestamp,
CNT int DEFAULT 0
);
INSERT INTO BOARD(SEQ, TITLE, WRITER, CONTENT) VALUES(1,'title1','writer1','content1');
INSERT INTO BOARD(SEQ, TITLE, WRITER, CONTENT) VALUES(2,'title2','writer2','content2');
SELECT * FROM BOARD ORDER BY SEQ;
BoardVO.java
xxxxxxxxxx
import java.sql.Date;
public class BoardVO {
private int seq;
private String title;
private String writer;
private String content;
private Date regDate;
private int cnt;
public BoardVO() {
}
public BoardVO(int seq, String title, String writer, String content, Date regDate, int cnt) {
super();
this.seq = seq;
this.title = title;
this.writer = writer;
this.content = content;
this.regDate = regDate;
this.cnt = cnt;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "BoardVO [seq=" + seq + ", title=" + title + ", writer=" + writer + ", content"+ content + ", regdate=" + regDate + ", cnt=" + cnt +"]";
}
}
web.xml
xxxxxxxxxx
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<description></description>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>com.mvcboard.controller.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
xxxxxxxxxx
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
request.setCharacterEncoding("UTF-8"); // post 요청시 한글 처리
process(request, response);
}
xxxxxxxxxx
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request path 추출
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/"));
//System.out.println(path);
}
DispatcherServlet.java
xxxxxxxxxx
package com.mvcboard.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DispatcherServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
request.setCharacterEncoding("UTF-8"); // post 요청시 한글 처리
process(request, response);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request path 추출
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/"));
//System.out.println(path);
// request 처리
if(path.equals("/getBoardList.do")) {
System.out.println("/getBoardList.do");
}
}
}
마이바티스는 JDBC로 처리하는 상당 부분의 코드와 파라미터 설정 및 결과 매핑을 대신해줌
마이바티스는 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO를 설정해서 매핑하기 위해 XML과 애노테이션을 사용
쿼리 기반 웹 애플리케이션을 개발할 때 가장 많이 사용되는 SQL 매퍼(Mapper) 프레임워크
마이바티스를 사용하지 않고 직접 JDBC를 이용할 경우 문제점:
JDBC를 이용해서 직접 개발하기보다는 마이바티스와 같은 프레임워크를 사용하는 게 일반적
JDBC를 이용하여 프로그래밍을 하는 방식:
클래스나 JSP와 같은 코드 안에 SQL문을 작성하는 방식
따라서 SQL의 변경 등이 발생할 경우 프로그램을 수정해야 한다.
마이바티스에서는 SQL을 XML 파일에 작성하기 때문에, SQL의 변환이 자유롭고 가독성도 좋다.
MySql
xxxxxxxxxx
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
xxxxxxxxxx
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
jspboard.mybatis.conifg.xml
xxxxxxxxxx
<?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="jspboard.BoardVO" alias="boardVO"/>
</typeAliases>
<environments default="develpment">
<environment id="develpment">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/javadb" />
<property name="username" value="root" />
<property name="password" value="rootpass" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="jspboard/mybatis/mapper/sample.xml"/>
</mappers>
</configuration>
jspboard.mybatis.mapper.sample.xml
xxxxxxxxxx
<?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="sample">
<select id="getCount" resultType="int">
<![CDATA[
select count(*) from board
]]>
</select>
<select id="getBoardMap" parameterType="int" resultType="hashmap">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board where seq = #{seq}
]]>
</select>
<select id="getBoardVO" parameterType="int" resultType="jspboard.BoardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board where seq = #{seq}
]]>
</select>
<select id="getBoardListMap" resultType="hashmap">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board order by seq desc
]]>
</select>
<select id="getBoardList" resultType="jspboard.BoardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board order by seq desc
]]>
</select>
<select id="getBoardSearch" parameterType="String" resultType="boardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board
where 1 = 1
]]>
<if test="title != null">
and title like CONCAT('%',#{title},'%')
</if>
<![CDATA[
order by seq desc
]]>
</select>
<select id="getBoardSearchMap" parameterType="Map" resultType="boardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board
where 1 = 1
]]>
<if test="title != null">
and title like CONCAT('%',#{title},'%')
</if>
<if test="writer != null">
and writer like CONCAT('%',#{writer},'%')
</if>
<![CDATA[
order by seq desc
]]>
</select>
</mapper>
xxxxxxxxxx
package jspboard.mybatis;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionManager {
public static SqlSessionFactory sqlSession;
static {
String resource = "jspboard/mybatis/config.xml";
Reader reader = null;;
try {
reader = Resources.getResourceAsReader(resource);
sqlSession = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static SqlSessionFactory getSqlSession() {
return sqlSession;
}
}
sample.jsp
xxxxxxxxxx
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="jspboard.BoardVO"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.ibatis.session.SqlSession"%>
<%@page import="jspboard.mybatis.SqlSessionManager"%>
<%@page import="org.apache.ibatis.session.SqlSessionFactory"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
SqlSessionFactory sqlSessionFactory = SqlSessionManager.getSqlSession();
SqlSession sqlSession = sqlSessionFactory.openSession();
%>
<h1>boardList - BoardVO</h1>
<%
List<BoardVO> boardList = sqlSession.selectList("board.getBoardList");
for(BoardVO board:boardList){
out.print(board + "<br>");
}
%>
<h1>boardList - HashMap</h1>
<%
List<HashMap> boardListMap = sqlSession.selectList("board.getBoardListMap");
for(HashMap board:boardListMap){
out.print(board + "<br>");
}
%>
<h1>board - BoardVO</h1>
<%
BoardVO boardVO = sqlSession.selectOne("board.getBoardVO", 1);
out.print(boardVO + "<br>");
%>
<h1>board - HashMap</h1>
<%
HashMap boardMap = sqlSession.selectOne("board.getBoardMap", 1);
out.print(boardMap + "<br>");
%>
<h1>boardSearch - BoardVO</h1>
<%
boardList = sqlSession.selectList("board.getBoardSearch", "2");
for(BoardVO board:boardList){
out.print(board + "<br>");
}
%>
<h1>boardSearchMap - BoardVO</h1>
<%
Map<String,String> searchV = new HashMap<String,String>();
searchV.put("title","22");
searchV.put("writer","wr");
boardList = sqlSession.selectList("board.getBoardSearch", searchV);
for(BoardVO board:boardList){
out.print(board + "<br>");
}
%>
xxxxxxxxxx
[MySQL]
title like CONCAT('%',#{keyword},'%')
[Oracle]
title like '%' || #{keyword} || '%'
[MSSQL]
title like '%' + #{keyword} + '%'
x<?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="jspboard.BoardVO" alias="BoardVO"/>
</typeAliases>
<environments default="develpment">
<environment id="develpment">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/javadb" />
<property name="username" value="root" />
<property name="password" value="rootpass" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="jspboard/mybatis/mapper/sample.xml"/>
<mapper resource="jspboard/mybatis/mapper/board.xml"/>
</mappers>
</configuration>
xxxxxxxxxx
<?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="board">
<select id="getCount" resultType="int">
<![CDATA[
select count(*) from board
]]>
</select>
<select id="getBoard" parameterType="BoardVO" resultType="BoardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board where seq = #{seq}
]]>
</select>
<select id="getBoardList" resultType="BoardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board order by seq desc
]]>
</select>
<select id="getBoardSearch" parameterType="String" resultType="BoardVO">
<![CDATA[
select seq,title,writer,content,regDate,cnt from board
where 1 = 1
]]>
<if test="title != null">
and title like CONCAT('%',#{title},'%')
</if>
<![CDATA[
order by seq desc
]]>
</select>
<insert id="insertBoard" parameterType="BoardVO">
INSERT INTO board (title,writer,content)
VALUES (#{title},#{writer},#{content})
</insert>
<update id="updateBoard" parameterType="BoardVO">
UPDATE board
SET title = #{title}, content = #{content}
WHERE seq = #{seq}
</update>
<delete id="deleteBoard" parameterType="BoardVO">
DELETE FROM board
WHERE seq = #{seq}
</delete>
</mapper>
xpackage jspboard;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import jspboard.mybatis.SqlSessionManager;
public class BoardDAO{
// Mybtis
SqlSessionFactory sqlSessionFactory = SqlSessionManager.getSqlSession();
SqlSession sqlSession = sqlSessionFactory.openSession(true); // true : AutoCommit
//SqlSession sqlSession = sqlSessionFactory.openSession(); // CUD 작업 후 sqlSession.commit() 필요
// Method
// BoardList
public List<BoardVO> getBoardList() {
System.out.println("getBoardList()");
List<BoardVO> boardList = sqlSession.selectList("board.getBoardList");
return boardList;
}
// BOARD_GET
public BoardVO getBoard(BoardVO vo) {
System.out.println("getBoard()");
BoardVO board = sqlSession.selectOne("board.getBoard",vo);
return board;
}
// BOARD_INSERT
public void insertBoard(BoardVO vo) {
System.out.println("insertBoard()");
int rs = sqlSession.insert("board.insertBoard",vo);
System.out.println(rs + "개 insert");
//sqlSession.commit(); // AutoCommit 아닐 시 넣어 주어야 함
}
// BOARD_UPDATE
public void updateBoard(BoardVO vo) {
System.out.println("updatetBoard()");
int rs = sqlSession.update("board.updateBoard",vo);
System.out.println(rs + "개 update");
}
// BOARD_DELETE
public void deleteBoard(BoardVO vo) {
System.out.println("deleteBoard()");
int rs = sqlSession.delete("board.deleteBoard",vo);
System.out.println(rs + "개 delete");
}
}
DispatcherServlet.java
xxxxxxxxxx
if(path.equals("/getBoardList.do")) {
System.out.println("/getBoardList.do");
BoardVO vo = new BoardVO();
BoardDAO boardDAO = new BoardDAO();
List<BoardVO> boardList = boardDAO.getBoardList();
HttpSession httpSession = request.getSession();
httpSession.setAttribute("boardList", boardList);
response.sendRedirect("getBoardList.jsp");
}
getBoardList.jsp
xxxxxxxxxx
<%@page import="com.mvcboard.vo.BoardVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
List<BoardVO> boardList = (List)session.getAttribute("boardList");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>getBoardList.jsp</title>
<style>
th {width:100px; background-color: rgb(200, 150, 200); align:center;}
.title { width:300px;}
</style>
</head>
<body>
<center>
<h1>Board List</h1>
<h3>Login: Test <a href="logout.do">[Log-out]</a></h3>
<hr>
<!-- Search -->
<form action="getBoardList.do" method="post">
<table border="1" cellpadding="0" cellspacing="0" width="700">
<tr>
<td align="right">
<select name="searchType">
<option value="TITLE">Title</option>
<option value="CONTENT">Content</option>
</select>
<input type="text" name="searchKeyword" >
<input type="submit" value="Search" >
</td>
</table>
</form>
<!-- List -->
<table border="1" cellpadding="0" cellspacing="0" width="700">
<tr>
<th>Seq</th>
<th class="title">Title</th>
<th>Writer</th>
<th>RegDate</th>
<th>CNT</th>
</tr>
<% for(BoardVO board : boardList) {%>
<tr align="center">
<td><%=board.getSeq() %></th>
<td align="left"> <a href="getBoard.do?seq=<%=board.getSeq()%>"><%=board.getTitle() %></a></th>
<td><%=board.getWriter() %></th>
<td><%=board.getRegDate() %></th>
<td><%=board.getCnt() %></th>
</tr>
<%} %>
</table>
<hr>
<a href="insertBoard.jsp">[Board Write]</a>
<hr>
</center>
</body>
</html>
DispatcherServlet.java
xxxxxxxxxx
else if(path.equals("/getBoard.do")) {
System.out.println("/getBoard.do");
String seq = request.getParameter("seq");
BoardVO vo = new BoardVO();
vo.setSeq(Integer.parseInt(seq));
BoardDAO boardDAO = new BoardDAO();
BoardVO board = boardDAO.getBoard(vo);
HttpSession httpSession = request.getSession();
httpSession.setAttribute("board", board);
response.sendRedirect("getBoard.jsp");
}
getBoard.jsp
xxxxxxxxxx
<%@page import="com.mvcboard.vo.BoardVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
BoardVO board = (BoardVO)session.getAttribute("board");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>getBoard.jsp</title>
<style>
th {width:100px; background-color: rgb(200, 150, 200); align:center;}
</style>
</head>
<body>
<center>
<h1>Board View</h1>
<a href="logout.do">[Log-out]</a>
<hr>
<form action="updateBoard.do" method="post">
<input type="hidden" name="seq" value="<%=board.getSeq() %>">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Title</td>
<td> <input type="text" name="title" value="<%=board.getTitle() %>" size="40" /></td>
</tr>
<tr>
<th>Writer</td>
<td> <%=board.getWriter() %></td>
</tr>
<tr>
<th>Content</td>
<td><textarea name="content" cols="40" rows="10"><%=board.getContent() %></textarea></td>
</tr>
<tr>
<th>RegDate</td>
<td> <%=board.getRegDate() %></td>
</tr>
<tr>
<th>Count</td>
<td> <%=board.getCnt() %></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Board Modify" /></td>
</tr>
</table>
</form>
<hr>
<a href="insertBoard.jsp">[Board Write]</a>
<a href="deleteBoard.do?seq=<%=board.getSeq()%>">[Board Delete]</a>
<a href="getBoardList.do">[Board List]</a>
<hr>
</center>
</body>
</html>
insertBoard.jsp
xxxxxxxxxx
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>insertBoard.jsp</title>
<style>
th {width:100px; background-color: rgb(200, 150, 200); align:center;}
</style>
</head>
<body>
<center>
<h1>Board Write</h1>
<a href="logout.do">[Log-out]</a>
<hr>
<form action="insertBoard.do" method="post">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Title</td>
<td><input type="text" name="title" size="40" /></td>
</tr>
<tr>
<th>Writer</td>
<td><input type="text" name="writer" size="20" /></td>
</tr>
<tr>
<th>Content</td>
<td><textarea name="content" cols="40" rows="10"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Board Write" /></td>
</tr>
</table>
</form>
<hr>
<a href="getBoardList.do">[Board List]</a>
<hr>
</center>
</body>
</html>
DispatcherServlet.java
xxxxxxxxxx
else if(path.equals("/insertBoard.do")) {
System.out.println("/insertBoard.do");
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String content = request.getParameter("content");
BoardVO vo = new BoardVO();
vo.setTitle(title);
vo.setWriter(writer);
vo.setContent(content);
BoardDAO boardDAO = new BoardDAO();
boardDAO.insertBoard(vo);
response.sendRedirect("getBoardList.do");
}
DispatcherServlet.java
xxxxxxxxxx
else if(path.equals("/updateBoard.do")) {
System.out.println("/updateBoard.do");
String title = request.getParameter("title");
String content = request.getParameter("content");
String seq = request.getParameter("seq");
BoardVO vo = new BoardVO();
vo.setTitle(title);
vo.setContent(content);
vo.setSeq(Integer.parseInt(seq));
BoardDAO boardDAO = new BoardDAO();
boardDAO.updateBoard(vo);
response.sendRedirect("getBoardList.do");
}
DispatcherServlet.java
xxxxxxxxxx
else if(path.equals("/deleteBoard.do")) {
System.out.println("/deleteBoard.do");
String seq = request.getParameter("seq");
BoardVO vo = new BoardVO();
vo.setSeq(Integer.parseInt(seq));
BoardDAO boardDAO = new BoardDAO();
boardDAO.deleteBoard(vo);
response.sendRedirect("getBoardList.do");
}
http://localhost:8080/MVCBoard/getBoardList.do