[Spring-F.] 29. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법5(SqlMap Spring전용)
소스 코드 위주로 소개하겠다.
[실험 결과]
1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02
[이전 게시글]
1. [Spring-F.] 28. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법4(SqlMap Spring전용)
41. 결과
XML 방식의 XML Mapping으로 구성하여 동작한 결과이다.
그림 25. 결과 5번
그림 26. 프로젝트 구성도
42. web.xml - 기본값
web.xml 파일은 변경하지 않았다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
43. com.example.spbatis.db - SqlMapSessionFactory.java
package com.example.spbatis.db;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.example.spbatis.model.CompUsers;
import oracle.jdbc.pool.OracleDataSource;
public class SqlMapSessionFactory {
private static SqlMapSessionFactory factory = new SqlMapSessionFactory();
private final static String driverName = "oracle.jdbc.driver.OracleDriver";
private final static String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
private final static String userName = "사용자계정명";
private final static String userPassword = "비밀번호";
public static SqlSessionFactory ssf;
public static SqlMapSessionFactory getInstance() {
return factory;
}
private SqlMapSessionFactory () { }
static {
/* 방법1
DataSource dataSource = getOracleDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(CompUsersMapper.class);
ssf = new SqlSessionFactoryBuilder().build(configuration);
*/
}
public static SqlSessionFactory getSqlSessionFactory(){
/* 방법2: 공식 메뉴얼 참고 */
DataSource dataSource = getOracleDataSource();
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); // Spring Framework만 지원
factoryBean.setDataSource(dataSource);
try {
//쿼리가 정의된 xml 파일들의 위치 지정
factoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("com/example/spbatis/mapper/*.xml")
);
ssf = factoryBean.getObject();
// 클래스 등록
// ssf.getConfiguration().addMapper(CompUsersMapper.class);
} catch (Exception e) {
e.printStackTrace();
}
// 방법 1, 방법 2 공통
return ssf;
}
/*
* Description: 순정 오라클 데이터소스
*/
private static DataSource getOracleDataSource(){
OracleDataSource oracleDS = null;
try {
oracleDS = new OracleDataSource();
oracleDS.setURL(dbUrl);
oracleDS.setUser(userName);
oracleDS.setPassword(userPassword);
} catch (SQLException e) {
e.printStackTrace();
}
return oracleDS;
}
}
파일명: SqlMapSessionFactory.java
[첨부(Attachments)]
44. com.example.spbatis.mapper - CompUsersMapper.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="com.example.spbatis.mapper">
<select id="allCompUsers" resultType="com.example.spbatis.model.CompUsers">
select * from comp_users
</select>
<!--
<select id="allAddress" resultType="com.edu.db.AddressDto">
select * from addressbook
</select>
<select id="selectAddress" parameterType="Integer" resultType="com.edu.db.AddressDto">
select NUM, NAME, ADDRESS, BIRTHDATE
from addressbook
where num=#{num}
</select>
<insert id="insertAddress" parameterType="com.edu.db.AddressDto">
insert into
addressbook(NAME, ADDRESS, BIRTHDATE)
values
(#{name},#{address},#{birthdate})
</insert>
<delete id="deleteAddress" parameterType="Integer">
DELETE FROM AddressBook
WHERE NUM = #{num}
</delete>
<update id="updateAddress" parameterType="com.edu.db.AddressDto" >
update addressbook
set birthdate = #{birthdate}, name = #{name}, address =#{address}
where num = #{num}
</update>
-->
</mapper>
파일명: CompUsersMapper.xml
[첨부(Attachments)]
45. com.example.spbatis.dao - CompUsersDao.java
package com.example.spbatis.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.example.spbatis.db.SqlMapSessionFactory;
import com.example.spbatis.model.CompUsers;
public class CompUsersDao {
SqlSessionFactory factory = SqlMapSessionFactory.getSqlSessionFactory();
public CompUsersDao() {
}
// SQL 세션 열기
public List<CompUsers> selectAddress() {
List<CompUsers> user = null;
try (SqlSession session = factory.openSession()) {
user = session.selectList("com.example.spbatis.mapper.allCompUsers");
session.close();
// System.out.println("계정명:" + user.getUsername());
}
return user;
}
}
파일명: CompUsersDao.java
[첨부(Attachments)]
46. com.example.spbatis.service - CompUsersService.java
package com.example.spbatis.service;
import java.util.List;
import com.example.spbatis.dao.CompUsersDao;
import com.example.spbatis.model.CompUsers;
public class CompUsersService {
private CompUsersDao dao = null;
public CompUsersService() {
dao = new CompUsersDao();
}
public List<CompUsers> getAllCompUsers() {
return dao.selectAddress();
}
}
파일명: CompUsersService.java
[첨부(Attachments)]
47. com.example.spbatis - HomeController.java
package com.example.spbatis;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.spbatis.service.CompUsersService;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
private CompUsersService compUserService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home5 - Java(XML Mappers)! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
compUserService = new CompUsersService();
model.addAttribute("serverTime", formattedDate );
model.addAttribute("list", compUserService.getAllCompUsers()) ;
return "home";
}
}
파일명: HomeController.java
[첨부(Attachments)]
48. view - home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
<h3>SqlMapSessionFactory 방식(Java - XML Mapper - Spring 전용 버전)</h3>
<c:forEach items="${list }" var="val" >
${val.username} /
${val.password} /
${val.enabled }<br>
</c:forEach>
<c:if test="${empty list }">
${"데이터가 존재하지않아요."}
</c:if>
</body>
</html>
파일명: home.jsp
[첨부(Attachments)]
* 맺음글(Conclusion)
조금 작성하는데 힘이 들었지만. MyBatis 하나 셋팅에는 다양한 방법이 지원된다는 것을 알 수 있었다.
* 참고 자료(References)
1. mybatis-spring - 마이바티스 스프링 연동모듈 | 시작하기, https://mybatis.org/spring/ko/getting-started.html, Accessed by 2020-10-02, Last Modified 2020-06-05.
[비고] - 공식 사이트이다. (이 메뉴얼만 가지고는 다 안 될 수도 있다.)
2. 스프링프레임워크 Java config로 MyBatis 사용하기, https://offbyone.tistory.com/381, Accessed by 2020-10-02, Last Modified 2019-03-17.
3. [mybatis] 다중 Database Setting, https://wfreud.tistory.com/310, Accessed by 2020-10-02, Last Modified 2019-03-21.
4. maven프로젝트 src/main/resource경로의 파일 읽기, https://blog.naver.com/down83/50092131189, Accessed by 2020-10-02, Last Modified 2010-07-13.
5. MyBatis List와 Map으로 데이터 불러오기, https://smujihoon.tistory.com/112, Accessed by 2020-10-02, Last Modified 2019-02-11.
5. [Mybatis] root-context.xml 자료(Oracle), https://datamod.tistory.com/81, Accessed by 2020-10-02, Last Modified 2018-05-20.
6. 7. 공용 클래스 작성 - commonDAo, https://tapasnote.tistory.com/21?category=697717, Accessed by 2020-10-02, Last Modified 2017-04-12.
7. DatsSource, 커넥션 풀을 이용한 DB 연결, https://m.blog.naver.com/PostView.nhn?blogId=2hyoin&logNo=220647895962, Accessed by 2020-10-02, Last Modified 2016-03-07.
8. MyBatis tutorial - Introductory MyBatis tutorial, http://zetcode.com/db/mybatis/, Accessed by 2020-10-02, Last Modified 2020-07-06.