지구정복
[myBatis] 1/21 | Model1 게시판 myBatis로 만들기, 어노테이션(기본sql문, 게시판만들기), Maven(개념, 사용) 본문
[myBatis] 1/21 | Model1 게시판 myBatis로 만들기, 어노테이션(기본sql문, 게시판만들기), Maven(개념, 사용)
nooh._.jl 2021. 1. 21. 17:351. 게시판 myBatis로 만들기
1. Model1 방식으로 myBatis로 게시판만들기 (설정파일 xml)
먼저 예전에 사용한 Model1Ex01 게시판 자바프로젝트를 복사해서
MyBatisModel1Ex01 로 이름을 변경하고 properties - Web Project Settings - Context root를 프로젝트이름과 같이 바꿔준다.
그리고 mybais 라이브러리를 웹콘텐츠 - 웹inf - lib폴더에 다 넣어주고
log4j.xml, myBatisConfig.xml을 자바리소스 - src에 넣어준다.
또한 매핑할 sql문이 적힌 mapper.xml을 복하해서 src폴더에 넣어주고 board.xml으로 이름을 변경한다.
다음과 같이 코딩한다.
-BoardTO.java
package model1;
public class BoardTO{
private String seq;
private String subject;
private String writer;
private String mail;
private String password;
private String content;
private String hit;
private String wip;
private String wdate;
private int wgap;
public String getSeq(){
return seq;
}
public String getSubject(){
return subject;
}
public String getWriter(){
return writer;
}
public String getMail(){
return mail;
}
public String getPassword(){
return password;
}
public String getContent(){
return content;
}
public String getHit(){
return hit;
}
public String getWip(){
return wip;
}
public String getWdate(){
return wdate;
}
public int getWgap(){
return wgap;
}
public void setSeq(String seq){
this.seq = seq;
}
public void setSubject(String subject){
this.subject = subject;
}
public void setWriter(String writer){
this.writer = writer;
}
public void setMail(String mail){
this.mail = mail;
}
public void setPassword(String password){
this.password = password;
}
public void setContent(String content){
this.content = content;
}
public void setHit(String hit){
this.hit = hit;
}
public void setWip(String wip){
this.wip = wip;
}
public void setWdate(String wdate){
this.wdate = wdate;
}
public void setWgap(int wgap){
this.wgap = wgap;
}
}
-board.xml
<?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="mybatis">
<!-- list -->
<select id="list" resultType="model1.BoardTO">
select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, hit, datediff(now(), wdate) wgap
from board1
order by seq desc;
</select>
<!-- view -->
<select id="view" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, subject, writer, mail, wip, wdate, hit, content
from board1
where seq = #{seq};
</select>
<update id="view_hit" parameterType="model1.BoardTO">
update board1 set hit = hit+1
where seq = #{seq};
</update>
<!-- write_ok -->
<insert id="write_ok" parameterType="model1.BoardTO">
insert into board1
values (0, #{subject}, #{writer}, #{mail}, #{password}, #{content}, 0, #{wip}, now() );
</insert>
<!-- modify -->
<select id="modify" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, writer, subject, content, mail
from board1 where seq = #{seq};
</select>
<!-- modify_ok -->
<update id="modify_ok" parameterType="model1.BoardTO">
update board1 set subject = #{subject}, content = #{content}, mail = #{mail}
where seq = #{seq} and password = #{password};
</update>
<!-- delete -->
<select id="delete" parameterType="model1.BoardTO" resultType="model1.BoardTO">
select seq, subject, writer
from board1 where seq = #{seq};
</select>
<!-- delete_ok -->
<delete id="delete_ok" parameterType="model1.BoardTO">
delete
from board1
where seq = #{seq} and password = #{password};
</delete>
</mapper>
-BoardMyBatisDAO.java
package model1;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class BoardMyBatisDAO{
private SqlSession sqlSession;
public BoardMyBatisDAO(){
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.sqlSession = sqlSessionFactory.openSession( true );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
//write
public void boardWrite(){}
//write_ok
public int boardWriteOk( BoardTO to ){
int flag = 1;
int result = sqlSession.insert( "write_ok", to );
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
//list
public ArrayList<BoardTO> boardList(){
ArrayList<BoardTO> boardLists = (ArrayList)sqlSession.selectList( "list" );
if( sqlSession != null ) sqlSession.close();
return boardLists;
}
//view
public BoardTO boardView( BoardTO to ){
sqlSession.update( "view_hit", to );
to = sqlSession.selectOne( "view", to );
if( sqlSession != null ) sqlSession.close();
return to;
}
//delete
public BoardTO boardDelete( BoardTO to ){
to = sqlSession.selectOne( "delete", to );
if( sqlSession != null ) sqlSession.close();
return to;
}
//delete_ok
public int boardDeleteOk( BoardTO to ){
int flag = 1;
int result = sqlSession.delete( "delete_ok", to );
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
//modify
public BoardTO boardModify( BoardTO to ){
to = sqlSession.selectOne( "modify", to );
if( sqlSession != null ) sqlSession.close();
return to;
}
//modify_ok
public int boardModifyOk( BoardTO to ){
int flag = 1;
int result = sqlSession.update( "modify_ok", to );
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
}
-myBatisConfig.xml
<?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>
<environments default="maraidb2">
<environment id="maraidb1">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3307/project" />
<property name="username" value="project" />
<property name="password" value="123456"/>
</dataSource>
</environment>
<environment id="maraidb2">
<transactionManager type="JDBC" />
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/mariadb2" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="model1/board.xml" />
</mappers>
</configuration>
-board_list1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%@ page import="java.util.ArrayList" %>
<%
BoardMyBatisDAO dao = new BoardMyBatisDAO();
ArrayList<BoardTO> lists = dao.boardList();
int totalRecord = lists.size();
StringBuffer sbHtml = new StringBuffer();
for( BoardTO to : lists ) {
String seq = to.getSeq();
String subject = to.getSubject();
String writer = to.getWriter();
String wdate = to.getWdate();
String hit = to.getHit();
int wgap = to.getWgap();
sbHtml.append( " <tr> " );
sbHtml.append( " <td> </td> " );
sbHtml.append( " <td>" + seq + "</td> " );
sbHtml.append( " <td class='left'> ");
sbHtml.append( " <a href='board_view1.jsp?seq=" + seq + "'>" + subject + "</a> ");
if( wgap == 0 ) {
sbHtml.append( " <img src='../../images/icon_hot.gif' alt='HOT'> ");
}
sbHtml.append( " </td> " );
sbHtml.append( " <td>" + writer + "</td> " );
sbHtml.append( " <td>" + wdate + "</td> " );
sbHtml.append( " <td>" + hit + "</td> " );
sbHtml.append( " <td> </td> " );
sbHtml.append( " </tr> " );
}
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../../css/board_list.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<div class="contents_sub">
<div class="board_top">
<div class="bold">총 <span class="txt_orange"><%= totalRecord %></span>건</div>
</div>
<!--게시판-->
<div class="board">
<table>
<tr>
<th width="3%"> </th>
<th width="5%">번호</th>
<th>제목</th>
<th width="10%">글쓴이</th>
<th width="17%">등록일</th>
<th width="5%">조회</th>
<th width="3%"> </th>
</tr>
<%= sbHtml %>
</table>
</div>
<!--//게시판-->
<div class="align_right">
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'" />
</div>
</div>
</div>
<!--//하단 디자인 -->
</body>
</html>
-board_view1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding( "utf-8" );
BoardTO to = new BoardTO();
to.setSeq( request.getParameter( "seq" ) );
to.setSubject( "" );
to.setWriter( "" );
to.setMail( "" );
to.setWip( "" );
to.setWdate( "" );
to.setHit( "" );
to.setContent( "" );
BoardMyBatisDAO dao = new BoardMyBatisDAO();
to = dao.boardView( to );
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../../css/board_view.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<div class="contents_sub">
<!--게시판-->
<div class="board_view">
<table>
<tr>
<th width="10%">제목</th>
<td width="60%"><%= to.getSubject() %></td>
<th width="10%">등록일</th>
<td width="20%"><%= to.getWdate() %></td>
</tr>
<tr>
<th>글쓴이</th>
<td><%= to.getWriter() %>(<%= to.getMail() %>)(<%= to.getWip() %>)</td>
<th>조회</th>
<td><%= to.getHit() %></td>
</tr>
<tr>
<td colspan="4" height="200" valign="top" style="padding: 20px; line-height: 160%"><%= to.getContent() %></td>
</tr>
</table>
</div>
<div class="btn_area">
<div class="align_left">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
</div>
<div class="align_right">
<input type="button" value="수정" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_modify1.jsp?seq=<%= to.getSeq() %>'" />
<input type="button" value="삭제" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_delete1.jsp?seq=<%= to.getSeq() %>'" />
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='board_write1.jsp'" />
</div>
</div>
<!--//게시판-->
</div>
</div>
<!-- 하단 디자인 -->
</body>
</html>
-board_write1.sjp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../../css/board_write.css">
<script type="text/javascript">window.onload = function() {
document.getElementById( 'submit1' ).onclick = function() {
if ( document.wfrm.info.checked == false ) {
alert( '동의를 해주세요' );
return false;
}
if ( document.wfrm.writer.value.trim() == '' ) {
alert( '글쓴이를 입력해주세요' );
return false;
}
if ( document.wfrm.subject.value.trim() == '' ) {
alert( '제목을 입력해주세요' );
return false;
}
if ( document.wfrm.password.value.trim() == '' ) {
alert( '비밀번호를 입력해주세요' );
return false;
}
document.wfrm.submit();
}
}
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_write1_ok.jsp" method="post" name="wfrm">
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top" colspan="3"><input type="text" name="writer" value="" class="board_view_input_mail" maxlength="5" /></td>
</tr>
<tr>
<th>제목</th>
<td colspan="3"><input type="text" name="subject" value="" class="board_view_input" /></td>
</tr>
<tr>
<th>비밀번호</th>
<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
<tr>
<th>내용</th>
<td colspan="3"><textarea name="content" class="board_editor_area"></textarea></td>
</tr>
<tr>
<th>이메일</th>
<td colspan="3"><input type="text" name="mail1" value="" class="board_view_input_mail"/> @ <input type="text" name="mail2" value="" class="board_view_input_mail"/></td>
</tr>
</table>
<table>
<tr>
<br />
<td style="text-align:left;border:1px solid #e0e0e0;background-color:f9f9f9;padding:5px">
<div style="padding-top:7px;padding-bottom:5px;font-weight:bold;padding-left:7px;font-family: Gulim,Tahoma,verdana;">※ 개인정보 수집 및 이용에 관한 안내</div>
<div style="padding-left:10px;">
<div style="width:97%;height:95px;font-size:11px;letter-spacing: -0.1em;border:1px solid #c5c5c5;background-color:#fff;padding-left:14px;padding-top:7px;">
1. 수집 개인정보 항목 : 회사명, 담당자명, 메일 주소, 전화번호, 홈페이지 주소, 팩스번호, 주소 <br />
2. 개인정보의 수집 및 이용목적 : 제휴신청에 따른 본인확인 및 원활한 의사소통 경로 확보 <br />
3. 개인정보의 이용기간 : 모든 검토가 완료된 후 3개월간 이용자의 조회를 위하여 보관하며, 이후 해당정보를 지체 없이 파기합니다. <br />
4. 그 밖의 사항은 개인정보취급방침을 준수합니다.
</div>
</div>
<div style="padding-top:7px;padding-left:5px;padding-bottom:7px;font-family: Gulim,Tahoma,verdana;">
<input type="checkbox" name="info" value="1" class="input_radio"> 개인정보 수집 및 이용에 대해 동의합니다.
</div>
</td>
</tr>
</table>
</div>
<div class="btn_area">
<div class="align_left">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
</div>
<div class="align_right">
<input type="button" id="submit1" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
-board_write1_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding("utf-8");
BoardTO to = new BoardTO();
to.setSubject( request.getParameter( "subject" ) );
to.setWriter( request.getParameter( "writer" ) );
to.setMail( "" );
if ( !request.getParameter( "mail1" ).equals("") && !request.getParameter( "mail2" ).equals("") ) {
to.setMail( request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" ) );
}
to.setPassword( request.getParameter( "password" ) );
to.setContent( request.getParameter( "content" ) );
to.setWip( request.getRemoteAddr() );
BoardMyBatisDAO dao = new BoardMyBatisDAO();
int flag = dao.boardWriteOk(to);
out.println( " <script type='text/javascript'> " );
if( flag == 0 ) {
out.println( " alert('글쓰기에 성공했습니다.'); " );
out.println( " location.href='board_list1.jsp;' " );
} else {
out.println( " alert('글쓰기에 실패했습니다.'); " );
out.println( " history.back(); " );
}
out.println( " </script> " );
%>
-board_delete1.jsp
<%@page import="model1.BoardDAO"%>
<%@page import="model1.BoardTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding( "utf-8" );
BoardTO to = new BoardTO();
String seq = request.getParameter( "seq" );
to.setSeq(seq);
BoardMyBatisDAO dao = new BoardMyBatisDAO();
to = dao.boardDelete(to);
seq = to.getSeq();
String subject = to.getSubject();
String writer = to.getWriter();
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../../css/board_write.css">
<script type="text/javascript">window.onload = function() {
document.getElementById( 'submit1' ).onclick = function() {
if( document.dfrm.password.value.trim() == '' ) {
alert( '비밀번호를 입력해주세요' );
return false;
}
document.dfrm.submit();
}
}
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_delete1_ok.jsp" method="post" name="dfrm">
<input type="hidden" name="seq" value="<%= seq %>">
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top" colspan="3"><input type="text" name="writer" value="<%= writer %>" class="board_view_input_mail" maxlength="5" readonly/></td>
</tr>
<tr>
<th>제목</th>
<td colspan="3"><input type="text" name="subject" value="<%= subject %>" class="board_view_input" readonly/></td>
</tr>
<tr>
<th>비밀번호</th>
<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
</table>
</div>
<div class="btn_area">
<div class="align_left">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
<input type="button" value="보기" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp?seq=<%=seq %>'" />
</div>
<div class="align_right">
<input type="button" id="submit1" value="삭제" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
-board_delete1_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding( "utf-8" );
BoardTO to = new BoardTO();
String seq = request.getParameter( "seq" );
String password = request.getParameter( "password" );
to.setSeq(seq);
to.setPassword(password);
BoardMyBatisDAO dao = new BoardMyBatisDAO();
int flag = dao.boardDeleteOk(to);
out.println( " <script type='text/javascript'> " );
if( flag == 0 ) {
out.println( " alert('글삭제에 성공했습니다.'); " );
out.println( " location.href='board_list1.jsp;' " );
} else if ( flag == 1 ) {
out.println( " alert('비밀번호가 틀립니다.'); " );
out.println( " history.back(); " );
} else {
out.println( " alert('글삭제에 실패했습니다.'); " );
out.println( " history.back(); " );
}
out.println( " </script> " );
%>
-board_modify1.jsp
<%@page import="model1.BoardDAO"%>
<%@page import="model1.BoardTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding( "utf-8" );
BoardTO to = new BoardTO();
String seq = request.getParameter( "seq" );
to.setSeq(seq);
BoardMyBatisDAO dao = new BoardMyBatisDAO();
to = dao.boardModify( to );
String writer = to.getWriter();
String subject = to.getSubject();
String content = to.getContent();
String mail[] = null;
if ( to.getMail().equals("") ) {
mail = new String[] { "", "" };
} else {
mail = to.getMail().split( "@" );
}
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../../css/board_write.css">
<script type="text/javascript">window.onload = function() {
document.getElementById( 'submit2' ).onclick = function() {
if ( document.mfrm.subject.value.trim() == '' ) {
alert( '제목을 입력해주세요' );
return false;
}
if ( document.mfrm.password.value.trim() == '' ) {
alert( '비밀번호를 입력해주세요' );
return false;
}
if ( document.mfrm.content.value.trim() == '' ) {
alert( '내용을 입력해주세요' );
return false;
}
document.mfrm.submit();
}
}
</script>
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<form action="board_modify1_ok.jsp" method="post" name="mfrm">
<input type="hidden" name="seq" value="<%= seq %>">
<div class="contents_sub">
<!--게시판-->
<div class="board_write">
<table>
<tr>
<th class="top">글쓴이</th>
<td class="top" colspan="3"><input type="text" name="writer" value="<%= writer %>" class="board_view_input_mail" maxlength="5" readonly/></td>
</tr>
<tr>
<th>제목</th>
<td colspan="3"><input type="text" name="subject" value="<%= subject %>" class="board_view_input" /></td>
</tr>
<tr>
<th>비밀번호</th>
<td colspan="3"><input type="password" name="password" value="" class="board_view_input_mail"/></td>
</tr>
<tr>
<th>내용</th>
<td colspan="3"><textarea name="content" class="board_editor_area"><%= content %></textarea></td>
</tr>
<tr>
<th>이메일</th>
<td colspan="3"><input type="text" name="mail1" value="<%= mail[0] %>" class="board_view_input_mail"/> @ <input type="text" name="mail2" value="<%= mail[1] %>" class="board_view_input_mail"/></td>
</tr>
</table>
</div>
<div class="btn_area">
<div class="align_left">
<input type="button" value="목록" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_list1.jsp'" />
<input type="button" value="보기" class="btn_list btn_txt02" style="cursor: pointer;" onclick="location.href='board_view1.jsp?seq=<%=seq %>'" />
</div>
<div class="align_right">
<input type="button" id="submit2" value="수정" class="btn_write btn_txt01" style="cursor: pointer;" />
</div>
</div>
<!--//게시판-->
</div>
</form>
</div>
<!-- 하단 디자인 -->
</body>
</html>
-board_modify1_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardMyBatisDAO" %>
<%
request.setCharacterEncoding( "utf-8" );
BoardTO to = new BoardTO();
String seq = request.getParameter( "seq" );
String password = request.getParameter( "password" );
String subject = request.getParameter( "subject" );
String content = request.getParameter( "content" );
String mail = "";
if ( !request.getParameter( "mail1" ).equals("") && !request.getParameter( "mail2" ).equals("") ) {
mail = request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" );
}
to.setSeq(seq);
to.setPassword(password);
to.setSubject(subject);
to.setContent(content);
to.setMail(mail);
BoardMyBatisDAO dao = new BoardMyBatisDAO();
int flag = dao.boardModifyOk(to);
out.println( " <script type='text/javascript'> " );
if( flag == 0 ) {
out.println( " alert('글수정에 성공했습니다.'); " );
out.println( " location.href='board_modify1.jsp?seq=" + seq + "' " );
} else if ( flag == 1 ) {
out.println( " alert('비밀번호가 틀립니다.'); " );
out.println( " history.back(); " );
} else {
out.println( " alert('글수정에 실패했습니다.'); " );
out.println( " history.back(); " );
}
out.println( " </script> " );
%>
2. 어노테이션 기법으로 myBatis 사용하기
1. 어노테이션으로 myBatis 사용
pojo: Plain Object Java Object: 순수자바
annotation은 @을 사용
새로운 자바프로젝트를 만든다. mybatis 라이브러리와 log4j.xml, myBatisConfig.xml을 복사해서 가져온다.
그리고 src에 model1패키지와 config 패키지를 만든다.
model1 안에 DeptTO.java를 만들고 아래와 같이 코딩한다.
package model1;
public class DeptTO{
private String deptno;
private String dname;
private String loc;
public String getDeptno(){
return deptno;
}
public String getDname(){
return dname;
}
public String getLoc(){
return loc;
}
public void setDeptno(String deptno){
this.deptno = deptno;
}
public void setDname(String dname){
this.dname = dname;
}
public void setLoc(String loc){
this.loc = loc;
}
}
그리고 config 패키지안에 SqlMapperInter.java 인터페이스를 만든다. 그리고 어노테이션에 아래와 같이 작성해주고 메서드를 선언한다.
package config;
import org.apache.ibatis.annotations.Select;
import model1.DeptTO;
public interface SqlMapperInter{
@Select( "select deptno, dname, loc from dept where deptno = 10" )
public DeptTO selectByDeptno();
}
-myBatisConfig.xml
<?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>
<environments default="maraidb">
<environment id="maraidb">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3307/sample" />
<property name="username" value="root" />
<property name="password" value="!123456"/>
</dataSource>
</environment>
</environments>
</configuration>
실행클래스는 아래와 같다.
-MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx01{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
DeptTO to = mapper.selectByDeptno();
System.out.println( to.getDeptno() );
System.out.println( to.getDname() );
System.out.println( to.getLoc() );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
이번에는 sql에 데이터값이 넘어올 때를 확인해보자.
-SqlMapperInter.java
package config;
import org.apache.ibatis.annotations.Select;
import model1.DeptTO;
public interface SqlMapperInter{
//@Select( "select deptno, dname, loc from dept where deptno = 10" )
//public DeptTO selectByDeptno();
@Select( "select deptno, dname, loc from dept where deptno = #{deptno}" )
public DeptTO selectByDeptno( String deptno );
}
-MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx01{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
DeptTO to = mapper.selectByDeptno( "20" );
System.out.println( to.getDeptno() );
System.out.println( to.getDname() );
System.out.println( to.getLoc() );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
이때 SqlMapperInter.java에서 메서드 오버로딩하면 안된다. 매개변수값이 다르면 메소드의 이름을 달리해서 사용하자.
Select문의 결과가 여러개일때
-SqlMapperInter.java
package config;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import model1.DeptTO;
public interface SqlMapperInter{
//@Select( "select deptno, dname, loc from dept where deptno = 10" )
//public DeptTO selectByDeptno();
@Select( "select deptno, dname, loc from dept where deptno = #{deptno}" )
public DeptTO selectByDeptno( String deptno );
//select결과 여러개일 때
@Select( "select deptno, dname, loc from dept" )
public List<DeptTO> selectList();
}
-MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx01{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
/*
* DeptTO to = mapper.selectByDeptno( "20" );
*
* System.out.println( to.getDeptno() ); System.out.println( to.getDname() );
* System.out.println( to.getLoc() );
*/
List<DeptTO> lists = mapper.selectList();
for( DeptTO list : lists ) {
System.out.print( list.getDeptno() + " / " );
System.out.print( list.getDname() + " / " );
System.out.println( list.getLoc() );
}
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
실습) 사원 이름의 첫 글자로 사원에 대한 정보 조회하기
select ... from emp where ename like 'S%';
-SqlMapperInter.java
package config;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import model1.EmpTO;
public interface SqlMapperInter1{
@Select( "select empno, ename, job, hiredate, sal, deptno from emp where ename like #{ename};")
public List<EmpTO> selectList( String ename );
}
-MyBatisEx02.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter1;
import model1.EmpTO;
public class MyBatisEx02{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface호출
sqlSession.getConfiguration().addMapper( SqlMapperInter1.class );
SqlMapperInter1 mapper = (SqlMapperInter1)sqlSession.getMapper( SqlMapperInter1.class );
List<EmpTO> lists = mapper.selectList( "S%" );
for( EmpTO list : lists ) {
System.out.print( list.getEmpno() + " / " );
System.out.print( list.getEname() + " / " );
System.out.print( list.getJob() + " / " );
System.out.print( list.getHiredate() + " / " );
System.out.print( list.getSal() + " / " );
System.out.println( list.getDeptno() );
}
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
DML 사용하기
insert문
-SqlMapperInter.java
package config;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import model1.DeptTO;
public interface SqlMapperInter{
@Insert( "insert into dept values ( #{deptno}, #{dname}, #{loc} )" )
public int insert( DeptTO to );
@Update( "update dept set dname=#{dname} where deptno=#{deptno}" )
public int update( DeptTO to );
@Delete( "delete from dept where deptno = #{deptno}" )
public int delete( DeptTO to );
}
-MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx01{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
DeptTO to = new DeptTO();
to.setDeptno( "70" );
to.setDname( "홍보" );
to.setLoc( "서울" );
int result = mapper.insert( to );
System.out.println( "결과: " + result );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
update문
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx02{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
DeptTO to = new DeptTO();
to.setDname( "졸려" );
to.setDeptno( "70" );
int result = mapper.update( to );
System.out.println( "결과: " + result );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
delete문
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
import model1.DeptTO;
public class MyBatisEx03{
public static void main(String[] args){
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
//mapper interface 호출하기
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
SqlMapperInter mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
DeptTO to = new DeptTO();
to.setDeptno( "70" );
int result = mapper.delete(to);
System.out.println( "결과: " + result );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
2. myBatis 어노테이션 기법사용해서 Model1 게시판 만들기
위에서 만든 MyBatisModel1Ex01 프로젝트를 복사해서 MyBatisModel1Ex02으로 만든다.
자바리소스 src폴더에 config 패키지를 만들고 그 안에 SqlMapperInter.java 인터페이스를 만든다.
수정할 것은 아래에 표시한 것만 하면된다.
-myBatisConfig.xml
<?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>
<environments default="maraidb2">
<environment id="maraidb1">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3307/project" />
<property name="username" value="project" />
<property name="password" value="123456"/>
</dataSource>
</environment>
<environment id="maraidb2">
<transactionManager type="JDBC" />
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/mariadb2" />
</dataSource>
</environment>
</environments>
</configuration>
-SqlMapperInter.java(인터페이스)
package config;
import java.util.ArrayList;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import model1.BoardTO;
public interface SqlMapperInter{
// list
@Select( "select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, hit, datediff(now(), wdate) wgap from board1 order by seq desc;" )
public ArrayList<BoardTO> boardList();
// view
@Update( "update board1 set hit = hit+1 where seq = #{seq}" )
public int boardViewHit(BoardTO to);
@Select( "select seq, subject, writer, mail, wip, wdate, hit, content from board1 where seq = #{seq};" )
public BoardTO boardView(BoardTO to);
// write_ok
@Insert( "insert into board1 values (0, #{subject}, #{writer}, #{mail}, #{password}, #{content}, 0, #{wip}, now() );" )
public int boardWriteOk(BoardTO to);
// modify
@Select( "select seq, writer, subject, content, mail from board1 where seq = #{seq};" )
public BoardTO boardModify(BoardTO to);
// modify_ok
@Update( "update board1 set subject = #{subject}, content = #{content}, mail = #{mail} where seq = #{seq} and password = #{password};" )
public int boardModifyOK(BoardTO to);
// delete
@Select( "select seq, subject, writer from board1 where seq = #{seq};" )
public BoardTO boardDelete(BoardTO to);
// delete_ok
@Delete( "delete from board1 where seq = #{seq} and password = #{password};" )
public int boardDeleteOK(BoardTO to);
}
-BoardMyBatisDAO.java
package model1;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import config.SqlMapperInter;
public class BoardMyBatisDAO{
private SqlSession sqlSession;
private SqlMapperInter mapper;
public BoardMyBatisDAO(){
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
this.sqlSession = sqlSessionFactory.openSession( true );
sqlSession.getConfiguration().addMapper( SqlMapperInter.class );
this.mapper = (SqlMapperInter)sqlSession.getMapper( SqlMapperInter.class );
} catch (IOException e) {
System.out.println( "에러: " + e.getMessage() );
} finally {
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
//write
public void boardWrite(){}
//write_ok
public int boardWriteOk( BoardTO to ){
int flag = 1;
int result = mapper.boardWriteOk(to);
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
//list
public ArrayList<BoardTO> boardList(){
ArrayList<BoardTO> boardLists = mapper.boardList();
if( sqlSession != null ) sqlSession.close();
return boardLists;
}
//view
public BoardTO boardView( BoardTO to ){
mapper.boardViewHit( to );
to = mapper.boardView(to);
if( sqlSession != null ) sqlSession.close();
return to;
}
//delete
public BoardTO boardDelete( BoardTO to ){
to = mapper.boardDelete(to);
if( sqlSession != null ) sqlSession.close();
return to;
}
//delete_ok
public int boardDeleteOk( BoardTO to ){
int flag = 1;
int result = mapper.boardDeleteOK(to);
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
//modify
public BoardTO boardModify( BoardTO to ){
to = mapper.boardModify(to);
if( sqlSession != null ) sqlSession.close();
return to;
}
//modify_ok
public int boardModifyOk( BoardTO to ){
int flag = 1;
int result = mapper.boardModifyOK(to);
if( result == 1 ) {
flag = 0;
}
if( sqlSession != null ) sqlSession.close();
return flag;
}
}
2. Maven
0. 개요
JSP/Java Framework
1. myBatis - SQL Mapper
2. spring - class를 풀링하는 framework
(클래스를 직접 new로 만들지 않고 이미 만들어진 클래스를 가져와서 사용하는 것)
=> 전자정부프레임워크의 핵심
Spring을 사용하기 위해서 필요한 것
1. Maven - 컴파일을 쉽게 처리하려고 만든 프레임워크
=>컴파일뿐만 아니라 라이브러리 접근도 쉽다.
1. Maven 개념
메이븐은 자바용 프로젝트 관리 도구이다.
메이븐은 컴파일과 빌드를 동시에 수행한다.(다양한 상황에서의 조건적인 컴파일)
메이븐은 라이브러리 관리 기능을 포함하고 있다.
메이븐은 중앙 저장소에서 라이브러리를 관리하고 의존성을 통해서 라이브러리를 공유할 수 있다.
메이븐은 필요한 라이브러리를 pom.xml에 정의해 놓고 개발자가 이를 관리하여 네트워크를 통해서
자동으로 다운로드 가능하다.
메이븐 저장소는 라이브버리 저장소이다. 스프링이나 전자정부표준 프레임워크를 사용하면
프로젝트의 기본 빌드 설정을 그대로 사용해서 문제될 것이 없으므로 손댈 것이 없다.
2. Maven 사용하기
mvnrepository.com/
위 사이트가 메이븐 저장소이고 이곳에 라이브러리들이 저장되어 있다.
검색창에 cos를 치고 아래와 사진과 같이 코드가 있는데 저 코드를 복사해서 가져다 쓰면 cos 라이브러리를 사용할 수 있다.
새로운 프로젝트를 만드는데 Maven Project를 만든다.
아래 사진처럼 여러가지 아키텍쳐중에서 선택된 것을 누르고 Next를 누른다.
아래처럼 그룹과 프로젝트명을 설정한다.
이때 아래처럼 이클립스에서 메이븐프로젝트를 만드는데 시간이 걸리므로 기다려야된다.
아래 pom.xml에서 라이브러리를 관리할 수 있다.
이제 다른 라이브러리를 가져와서 사용해보자.
( ctrl + shift + f를 누르면 코드 간격 조정 )
위 사이트에서 maridb 라고 검색하고 가장 위에 있는 것을 들어가자.
아래 Maven을 복사해서 pom.xml에 해당 내용을 추가한다.
코드를 추가하고 pom.xml을 저장하면 이클립스 오른쪽 밑에 다운로드가 시작된다.
만약 이렇게 원격으로 다운받는데 속도가 느리거나 다운로드받는 도중에 다른 것을 하다가 라이브러리 다운이 잘못되면 pom.xml에서 해당 코드를 지우고 실제 디렉터리에 가서 파일도 지워줘야 한다.
즉, 이클립스에서 라이브러리가 사라졌다고 해서 실질적으로 지워진 게 아니다.
디렉터리는 아래와 같다.
C:\Users\J\.m2\repository
이제 제대로 연동되었는지 확인하기 위해 mariaDB에서 emp테이블을 조회해보자.
-App.java
package com.exam.hello;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class App {
public static void main( String[] args ) {
String url = "jdbc:mysql://localhost:3307/sample";
String user = "root";
String password = "!123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
String sql = String.format("select deptno, dname, loc from dept");
//쿼리 실행
rs = stmt.executeQuery(sql);
//여러 행 데이터 읽기
while( rs.next() ) {
//System.out.println("결과처리");
System.out.println( rs.getString("deptno"));
System.out.println( rs.getString("dname"));
System.out.println( rs.getString("loc"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("에러: " + e.getMessage());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(rs!=null) try {rs.close();} catch(SQLException e) {}
if(conn!=null) try {conn.close();} catch(SQLException e) {}
if(stmt!=null) try {stmt.close();} catch(SQLException e) {}
}
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
10
ACCOUNTING
NEW YORK
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
OPERATIONS
BOSTON
50
영업
서울
60
개발
광주