[Spring-F.] 26. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법2(SqlMap-XML-XML 맵핑)
소스 코드 위주로 소개하도록 하겠다.
[실험 결과]
1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02
[이전 게시글]
1. [Spring-F.] 25. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법1(web.xml-Beans), 2020-10-02
15. 결과
2번째 실험에 대한 결과이다.
그림 19. 동작 결과
그림 20. 프로젝트 구성도
완성한 프로젝트의 구성도이다. 소스코드를 작성하는데 참고하면 도움이 될 것으로 보인다.
16. 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>
17. 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 방식(XML - 환경설정 - XML-Mappers)</h3>
<c:forEach items="${list }" var="val" >
${val.username} /
${val.password} /
${val.enabled }<br>
</c:forEach>
<c:if test="${empty list }">
${"데이터가 존재하지않아요."}
</c:if>
<h3>XML - web.xml 설정방식</h3>
<c:forEach items="${list2 }" var="val" >
${val.username} /
${val.password} /
${val.enabled }<br>
</c:forEach>
<c:if test="${empty list2 }">
${"데이터가 존재하지않아요."}
</c:if>
</body>
</html>
파일명: home.jsp
[첨부(Attachments)]
18. com.example.spbatis.mapper - mybatis-config.xml
Spring Boot가 아닌 이상, 참고로 해당 위치에 xml파일을 넣어줘야 한다.
예를 들면, the.getClass().getResources() 이런 함수를 활용해서 /src/main/resources 폴더를 생성하고 작업을 시도하려고 한다면,
실패할 것이다. 운이 좋아서 경로를 찾아서 빌드했을 때 동작이 되었다고 해도, 톰캣 서버에 올려버리면 경로를 못 찾아버리는 현상이 발생한다.
충분히 시간을 가지고, 태스트를 거친 후에 작성한 글이다.
<?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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 커넥션 풀(MyBatis) -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="username" value="UserName"/>
<property name="password" value="Password"/>
<property name="poolMaximumActiveConnections" value="20"/>
<property name="poolMaximumIdleConnections" value="20"/>
<property name="poolMaximumCheckoutTime" value="20000"/>
<property name="poolPingEnabled" value="true"/>
<property name="poolPingQuery" value="select 1"/>
<property name="poolPingConnectionsNotUsedFor" value="10000"/>
<property name="poolTimeToWait" value="15000"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/spbatis/mapper/CompUsersMapper.xml"/>
</mappers>
</configuration>
파일명: mybatis-config.xml
[첨부(Attachments)]
19. 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)]
20. com.example.spbatis.db - SqlMapSessionFactory.java
package com.example.spbatis.db;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlMapSessionFactory {
public SqlSessionFactory ssf;
public SqlMapSessionFactory () {
String resource = "com/example/spbatis/mapper/mybatis-config.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
ssf = new SqlSessionFactoryBuilder().build(is);
}
public SqlSessionFactory getSqlSessionFactory(){
return ssf;
}
}
파일명: SqlMapSessionFactory.java
[첨부(Attachments)]
21. 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 org.springframework.beans.factory.annotation.Autowired;
import com.example.spbatis.db.SqlMapSessionFactory;
import com.example.spbatis.model.CompUsers;
public class CompUsersDao {
private SqlMapSessionFactory ssfc;
private SqlSessionFactory factory;
public CompUsersDao() {
ssfc = new SqlMapSessionFactory();
factory = ssfc.getSqlSessionFactory();
}
// SQL 세션 열기
public List<CompUsers> selectAddress() {
SqlSession session = factory.openSession();
List<CompUsers> compDTO = session.selectList("com.example.spbatis.mapper.allCompUsers");
session.close();
return compDTO;
}
}
파일명: CompUsersDao.java
[첨부(Attachments)]
22. 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)]
23. 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 home2! 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)]
* 방법 3에 대한 글로 이동하기
3. [Spring-F.] 27. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법3(SqlMap-XML-Class)