어제 해보았던 실습을 똑같이 따라해봤다. (pom.xml세팅까지 다 끝냈다고 치고)
1. propertise 파일, config.xml이 필요
2. config.xml에 사용할 typeAlias(객체) 세팅, 사용할 Mapper.xml 세팅(sql명령어)
<?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="oracledb.test">
<!-- id: 메서드명 , parameterType : 인수, resultType : 리턴값 -->
<select id="today" resultType="date">
select SYSDATE from dual
</select>
<select id="calc" parameterType="hashmap" resultType="int">
select (#{num1} + #{num2}) * #{num3} from dual
</select>
<!-- 쿼리에 <, <= >, >=가 들어갈 경우에는 반드시 <![CDATA[ ]]> 섹션안에 써야 한다. 왜? 태그로 인식할
수 있기 때문 <![CDATA[ 명령 ]]> 섹션 안의 내용은 태그가 아닌 내용으로 인식되기 때문이다. -->
<select id="calcVO" parameterType="hashmap" resultType="testVO">
<![CDATA[
select SYSDATE AS today, (#{num1} + #{num2}) * #{num3} AS result, #{name} || '씨 반갑습니다.' AS message from dual
]]>
</select>
<select id="calcMap" parameterType="hashmap"
resultType="hashmap">
<![CDATA[
select SYSDATE AS today, (#{num1} + #{num2}) * #{num3} AS result, #{name} || '씨 반갑습니다.' AS message from dual
]]>
</select>
</mapper>
4가지 메서드를 만들었다.(testVO)
1) 오늘의 날짜
2) 계산
3) 오늘의날짜, 계산, 문자열 출력
4) 오늘의날짜, 계산, 문자열 출력(매개변수가 다르다)
3.
<body>
<%
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = null;
try{
// false 는 autoCommit 하지 않겠다는 의미.
sqlSession = sqlSessionFactory.openSession(false);
out.println("연결 성공 : " + sqlSession + "<br>");
// -----------------------------------------------------------------------
Date today = sqlSession.selectOne("oracledb.test.today");
out.println(today+"<br>");
HashMap<String,Integer>map = new HashMap<>();
map.put("num1", 3);
map.put("num2", 7);
map.put("num3", 2);
int result = sqlSession.selectOne("oracledb.test.calc", map);
out.println(result);
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
%>
</body>
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
이 부분을 따로 클래스 뺄 것이다. 계속 중복적으로 사용되기 때문(이전의 Connection과 같은 기능)(이전 게시글)
4. vo를 만들어 주고
mapper.xml을 보면 Date, int, String 이 반환 타입이다. 이걸보고 그대로 만들어 주면 된다.
5. DAO를 만든다. 이전 게시글과 같다.
6. 서비스 구현(어제와 다르다.)
import java.util.Date;
import java.util.HashMap;
import org.apache.ibatis.session.SqlSession;
import mybatis.MybatisApp;
import mybatis.memo.dao.TestDAO;
import mybatis.memo.vo.TestVO;
public class TestService {
//----------------------------------------------------------------------------
private static TestService instance = new TestService();
private TestService() {}
public static TestService getInstance() { return instance; }
//----------------------------------------------------------------------------
// 로직 1개당 메서드 1개씩 작성
// 현재 시간
public Date getToday() {
Date today = null;
SqlSession sqlSession = null;
try{
// false 는 autoCommit 하지 않겠다는 의미.
sqlSession = MybatisApp.getSqlSessionFactory().openSession(false);
// -----------------------------------------------------------------------
today = TestDAO.getInstance().getToday(sqlSession);
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
return today;
}
// 계산 결과
public int getCalc(int n1, int n2, int n3) {
int result = 0;
SqlSession sqlSession = null;
try{
// false 는 autoCommit 하지 않겠다는 의미.
sqlSession = MybatisApp.getSqlSessionFactory().openSession(false);
// -----------------------------------------------------------------------
HashMap<String, Integer> map = new HashMap<>();
map.put("num1", n1);
map.put("num2", n2);
map.put("num3", n3);
result = TestDAO.getInstance().getCalc(sqlSession, map);
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
return result;
}
// VO로 받아지는지
public TestVO getTestVO(int n1, int n2, int n3, String name) {
TestVO testVO = null;
SqlSession sqlSession = null;
try{
// false 는 autoCommit 하지 않겠다는 의미.
sqlSession = MybatisApp.getSqlSessionFactory().openSession(false);
// -----------------------------------------------------------------------
HashMap<String, String> map = new HashMap<>();
map.put("num1", n1 + "");
map.put("num2", n2 + "");
map.put("num3", n3 + "");
map.put("name", name);
testVO = TestDAO.getInstance().getCalcVO(sqlSession, map);
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
return testVO;
}
// Map으로 받아지는지
public HashMap<String, Object> getHashMap(int n1, int n2, int n3, String name) {
HashMap<String, Object> map = null;
SqlSession sqlSession = null;
try{
// false 는 autoCommit 하지 않겠다는 의미.
sqlSession = MybatisApp.getSqlSessionFactory().openSession(false);
// -----------------------------------------------------------------------
HashMap<String, String> map2 = new HashMap<>();
map2.put("num1", n1 + "");
map2.put("num2", n2 + "");
map2.put("num3", n3 + "");
map2.put("name", name);
map = TestDAO.getInstance().getCalcMap(sqlSession, map2);
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
return map;
}
}
이전 게시글은 두가지 db를 테스트 하기 위해 메서드를 만들고, 그 안에 mapper.xml에 구현된 메서드들을 사용해서
마지막 결과물만 딱 보이고자 하였다.
oracle만을 사용해서 mapper.xml의 메서드를 하나 하나씩 구현해보았다.
7. test.jsp
<body>
<%
// 서비스를 이용하여 원하는 결과를 얻어온다.
Date today = TestService.getInstance().getToday();
int result = TestService.getInstance().getCalc(1, 2, 3);
TestVO testVO = TestService.getInstance().getTestVO(1, 2, 3, "한사람");
HashMap<String, Object> hashMap = TestService.getInstance().getHashMap(2, 3, 4, "두사람");
// 출력을 EL로 하기 위하여 특정 영역에 저장을 한다.
request.setAttribute("today", today);
request.setAttribute("result", result);
request.setAttribute("testVO", testVO);
request.setAttribute("hashMap", hashMap);
%>
<h2>서버시간 : ${today }</h2>
<h2>서버시간 : <fmt:formatDate value="${today }" type="both" dateStyle="full" timeStyle="full"/> </h2>
<br />
<h2>계산 결과 : ${result }</h2>
<br />
<h2>VO로 받은 내용 : ${testVO }</h2>
<h2>VO로 받은 내용 1: ${testVO.today }</h2>
<h2>VO로 받은 내용 2: ${testVO.result }</h2>
<h2>VO로 받은 내용 3: ${testVO.message }</h2>
<br />
<h2>HashMap로 받은 내용 : ${hashMap }</h2>
<h2>HashMap로 받은 내용 1: ${hashMap.TODAY }</h2>
<h2>HashMap로 받은 내용 2: ${hashMap.RESULT }</h2>
<h2>HashMap로 받은 내용 3: ${hashMap.MESSAGE }</h2>
</body>
리턴 타입에 따라 Date, int, TestVO, HashMap 객체를 만들어주고, 서비스에서 매개변수를 입력하여 값을 저장하고
이를 EL으로 받기 위해 request에다가 저장한다.
body 부분에서 EL 타입으로 받는다.
testVO의 경우 객체로 받기 때문(TestVO에 정의된 변수는 Date, int, String)에 " . " 을 찍고 인자를 옆에 적어주면
그 값을 따로 따로 받을 수 있다.
Map으로 받는 것도 똑같은 매커니즘이다.
'Mybatis' 카테고리의 다른 글
Mybatis 실습 (0) | 2021.08.17 |
---|---|
MYBATIS 시작 (0) | 2021.08.17 |