kosta/Servlet,JSP,JDBC,MyBatis
[MyBatis] 기초 및 초기 설정
엑츄얼리
2022. 4. 22. 09:11
초기 설정 및 예제를 통한 실행 확인
앞 부분의 JSP, Servlet 초기 설정 + JDBC 초기 설정을 진행해주어야 한다.
오락가락하는데 이유를 모르겠다... 셋팅 하나씩 건드려봐도 찾을 수가 없다...
1. Project Structure => Module => add Application Server specific descriptor => tomcat 추가
2. run/debug Configurations => tomcat server 추가
* 1.이 실행이 안되면 JDBC도 그렇고 MyBatis도 제대로 작동하지 않는다. 용도가 조금 다른 것 같다....
아마 1.은 DB접근 권한 느낌이고, 2.는 웹 접근 권한 느낌...?
3. 필수 파일 및 라이브러리는 다음 선택된 부분이다. (mapper 부분은 유연하게 사용가능)
<?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">
<!--namespace는 변별성을 주기위해 앞에 붙여주는 느낌
아래의 listBoard를 호출하기 위해서는 mapper.BoardMapper.listBoard-->
<mapper namespace="mapper.BoardMapper">
<cache />
<!-- board table을 Board 객체로 반환-->
<select id="listBoard" resultType="Board">
select * from board order by seq desc
</select>
</mapper>
<Board.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>
<typeAliases>
<typeAlias type="bean.Board" alias="Board"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/oracle"/>
</dataSource>
<!-- 아래가 원본-->
<!-- <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="c##kosta236_2"/>-->
<!-- <property name="password" value="1234"/>-->
<!-- </dataSource>-->
</environment>
</environments>
<mappers>
<mapper resource="mapper/Board.xml"/>
</mappers>
</configuration>
<mybatis-config.xml>
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver"
maxActive="100" maxIdle="30" maxWait="10000"
name="jdbc/oracle" password="1234" type="javax.sql.DataSource"
url="jdbc:oracle:thin:@localhost:1521:XE"
username="c##kosta236_2"/>
</Context>
<context.xml>
* mybatis-config.xml 같은 경우 다른 파일에있는 mybatis-config.xml 접근 경로를 잘 맞춰줘도
디렉토리가 src/resource/mybatis-config.xml 가아니면 오류가 뜬다. 이것도 war 구조인듯 하다.
<%@ page import="bean.Board" %>
<%@ page import="java.util.List" %>
<%@ page import="bean.BoardDao2" %><%--
Created by IntelliJ IDEA.
User: JKM
Date: 2022-04-12
Time: 오후 4:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charet=UTF-8" language="java"
pageEncoding="utf-8"%>
<%
BoardDao2 dao = BoardDao2.getInstance();
List<Board> list = dao.listBoard();
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="#">글쓰기</a>
<table border="1">
<tr>
<td>글번호</td>
<td>제목</td>
<td>작성자</td>
<td>작성일자</td>
<td>조회수</td>
</tr>
<%
for (int i = 0; i < list.size(); i++) {
Board board = list.get(i);
%>
<tr>
<td><%=board.getSeq()%></td>
<td><a href="detail.jsp?seq=<%=board.getSeq()%>"><%=board.getTitle()%></a></td>
<td><%=board.getWriter()%></td>
<td><%=board.getRegdate()%></td>
<td><%=board.getHitcount()%></td>
</tr>
<%}%>
</table>
</body>
</html>
<list.jsp> -> 실행
package bean;
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.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class BoardDao2 {
private static BoardDao2 dao = new BoardDao2();
public static BoardDao2 getInstance() {
return dao;
}
public SqlSessionFactory getSqlSessionFactory() {
//mybatis-config.xml => SqlSesstionFactory로 변환하는 작업
String resource = "resource/mybatis-config.xml";
InputStream in = null;
try {
in = Resources.getResourceAsStream(resource);//mybatis-config.xml를 인푸트스트림이랑 연결시켜줬음.
} catch (Exception e) {
e.printStackTrace();
}
return new SqlSessionFactoryBuilder().build(in);
}
public List<Board> listBoard(){
SqlSession sqlSession = getSqlSessionFactory().openSession();
List<Board> list = null;
try {
list = sqlSession.selectList("mapper.BoardMapper.listBoard");//mapStatement 호출
} catch (Exception e) {
e.printStackTrace();
}finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return list;
}
}
<BoardDao2.java>
package bean;
import java.io.Serializable;
//Mybatis를 사용하려면 Serializable을 implements하여 직렬화를 수행해야한다.
public class Board implements Serializable {
private int seq;
private String title;
private String writer;
private String contents;
private String regdate;
private int hitcount;
@Override
public String toString() {
return "Board{" +
"seq=" + seq +
", title='" + title + '\'' +
", writer='" + writer + '\'' +
", contents='" + contents + '\'' +
", regdate='" + regdate + '\'' +
", hitcount=" + hitcount +
'}';
}
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 getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public int getHitcount() {
return hitcount;
}
public void setHitcount(int hitcount) {
this.hitcount = hitcount;
}
}
<Board.java>