이전 글에 mapper, config.xml, propertise 다 설정 되어 있다
1. MybatisApp(SqlSessionFactory)
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.ibatis.common.resources.Resources;
public class MybatisApp {
private static SqlSessionFactory mariaSessionFactory;
private static SqlSessionFactory oracleSessionFactory;
static {
String resource = "mybatis-mariadb-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
mariaSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
resource = "mybatis-oracle-config.xml";
try {
inputStream = Resources.getResourceAsStream(resource);
oracleSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getMariaSessionFactory() {
return mariaSessionFactory;
}
public static SqlSessionFactory getOracleSessionFactory() {
return oracleSessionFactory;
}
}
이전 글에
<body>
<%
String resource = "mybatis-oracle-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>");
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
e.printStackTrace();
}finally{
try {
if(sqlSession!=null) sqlSession.close();
}catch(Exception e){
e.printStackTrace();
}
}
%>
</body>
이렇게 오라클 db, mariadb에 연결을 했었다. 이 중 일부분을 자바 클래스로 빼서, 여러 개의 db에 한 개의 클래스를 통해 연결할 수 있도록 세팅해주었다.
2. VO
import java.util.Date;
import lombok.Data;
@Data
public class TestVO {
private Date today;
private int result;
private String message;
}
-> 말 그대로 데이터들을 받는 객체를 만든다고 보면 된다. '틀'을 만들때 필요하다.
lombok을 사용해서 getter,setter, toString까지 다 처리해준다.
3. DAO
인터페이스를 사용하여 db의 종류가 달라져도 적용할 수 있도록 구성하였다.
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import org.apache.ibatis.session.SqlSession;
import mybatis.vo.TestVO;
public interface TestDAO {
Date getToday(SqlSession sqlSession) throws SQLException;
int getCalc(SqlSession sqlSession, HashMap<String, Integer> map) throws SQLException;
TestVO getVO(SqlSession sqlSession, HashMap<String, String> map) throws SQLException;
HashMap<String, Object> getMap(SqlSession sqlSession, HashMap<String, String> map) throws SQLException;
}
Connection conn -> SqlSession으로 대체
-> Mapper.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="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>
1) 리턴 타입이 없고 void와 같이 매개변수가 없어도 되기 때문에 그냥 Sqlsession을 넣어주고, Date로 리턴하는 메서드
2) 리턴 타입이 int 이며 매개변수는 hashmap 값으로 넘어온다.
3) 리턴 타입이 testVO이며 매개변수는 hashmap
4) 리턴 타입이 hashmap이고 매개변수는 hashmap
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import org.apache.ibatis.session.SqlSession;
import mybatis.vo.TestVO;
public class TestDAOMariaImpl implements TestDAO{
private static TestDAO instance = new TestDAOMariaImpl();
private TestDAOMariaImpl() {
;
}
public static TestDAO getInstance() {
return instance;
}
@Override
public Date getToday(SqlSession sqlSession) throws SQLException {
return sqlSession.selectOne("mariadb.test.today");
}
@Override
public int getCalc(SqlSession sqlSession, HashMap<String, Integer> map) throws SQLException {
return sqlSession.selectOne("mariadb.test.calc");
}
@Override
public TestVO getVO(SqlSession sqlSession, HashMap<String, String> map) throws SQLException {
return sqlSession.selectOne("mariadb.test.calcVO");
}
@Override
public HashMap<String, Object> getMap(SqlSession sqlSession, HashMap<String, String> map) throws SQLException {
return sqlSession.selectOne("mariadb.test.calcMap");
}
}
4. Service
public class TestService {
//----------------------------------------------------------------------
private static TestService instance = new TestService();
private TestService() {
;
}
public static TestService getInstance() {
return instance;
}
//----------------------------------------------------------------------
public HashMap<String, Object> testOracle(){
HashMap<String, Object> map = new HashMap<>();
SqlSession sqlSession = null;
TestDAO testDAO = null;
try {
sqlSession = MybatisApp.getOracleSessionFactory().openSession(false);
testDAO = TestDAOOracleImpl.getInstance();
//-------------------------------------------------------------------
Date today = testDAO.getToday(sqlSession);
HashMap<String, Integer> map2 = new HashMap<>();
map2.put("num1", 15);
map2.put("num2", 10);
map2.put("num3", 2);
int calc = testDAO.getCalc(sqlSession, map2);
map.put("today", today);
map.put("calc", calc);
//-------------------------------------------------------------------
HashMap<String, String> map3 = new HashMap<>();
map3.put("num1", "22");
map3.put("num2", "22");
map3.put("num3", "12");
map3.put("name", "펭수");
TestVO testVO = testDAO.getVO(sqlSession, map3);
HashMap<String, Object> hashMap = testDAO.getMap(sqlSession, map3);
map.put("testVO", testVO);
map.put("hashMap", hashMap);
//-------------------------------------------------------------------
sqlSession.commit();
}catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
} finally {
try {
if(sqlSession!=null)sqlSession.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
public HashMap<String, Object> testMaria(){
HashMap<String, Object> map = new HashMap<>();
SqlSession sqlSession = null;
TestDAO testDAO = null;
try {
sqlSession = MybatisApp.getMariaSessionFactory().openSession(false);
testDAO = TestDAOMariaImpl.getInstance();
//-------------------------------------------------------------------
Date today = testDAO.getToday(sqlSession);
HashMap<String, Integer> map2 = new HashMap<>();
map2.put("num1", 15);
map2.put("num2", 10);
map2.put("num3", 2);
int calc = testDAO.getCalc(sqlSession, map2);
map.put("today", today);
map.put("calc", calc);
//-------------------------------------------------------------------
HashMap<String, String> map3 = new HashMap<>();
map3.put("num1", "22");
map3.put("num2", "22");
map3.put("num3", "12");
map3.put("name", "펭수");
TestVO testVO = testDAO.getVO(sqlSession, map3);
HashMap<String, Object> hashMap = testDAO.getMap(sqlSession, map3);
map.put("testVO", testVO);
map.put("hashMap", hashMap);
//-------------------------------------------------------------------
sqlSession.commit();
}catch (Exception e) {
sqlSession.rollback();
e.printStackTrace();
} finally {
try {
if(sqlSession!=null)sqlSession.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}
서비스의 기능들을 구현할 때에 각 객체에 어떤 부품들을 집어넣어서 조립을 완성시킬 수 있을지에 대해
계속 잊어버리고 있는데, 내가 좀 더 노력해야 할 것 같다.
초보자들은 아마도 이 매개변수(부품)을 넣어서 기능을 구현하는게 가장 힘든 부분이지 않을까 생각이 든다.
여기는 자바 코드이고, jsp에서는 어떤 사이트에서 변수를 submit하면 hidden으로 넘어가는 것도 있고,
여러 요소들을 가지고 넘어가는데, 다른 페이지에서 또 그 매개변수를 객체에 받아 페이지를 구현하고 또 다른 페이지에 넘겨준다.
공부 하면 할수록 어려운 파트가 객체 파트인거 같다.
객체가 여러개가 되고 객체 안에 객체가 들어가는 순간 머리가 백지가 된 것마냥 하얗게 된다...ㅋㅋ
5. test.jsp
<body>
<%
HashMap<String, Object> map1 = TestService.getInstance().testMaria();
HashMap<String, Object> map2 = TestService.getInstance().testOracle();
request.setAttribute("map1", map1);
request.setAttribute("map2", map2);
%>
<h2>MariaDB Test</h2>
오늘날짜 : ${map1.today } <br />
계산결과 : ${map1.calc } <br /><hr />
VO : ${map1.testVO } <br />
hashMap : ${map1.hashMap } <br /><hr />
<h2>OracleDB Test</h2>
오늘날짜 : ${map2.today } <br />
계산결과 : ${map2.calc } <br /><hr />
VO : ${map2.testVO } <br />
hashMap : ${map2.hashMap } <br /><hr />
</body>
'Mybatis' 카테고리의 다른 글
Mybatis 실습 2(복습) (0) | 2021.08.18 |
---|---|
MYBATIS 시작 (0) | 2021.08.17 |