[Spring-F.] 28. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법4(SqlMap Spring전용)
소스 코드 위주로 소개하도록 하겠다.
[실험 결과]
1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02
[이전 게시글]
1. [Spring-F.] 27. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법3(SqlMap-XML-Class) // 결과: 지원, 2020-10-02
33. 결과
작업한 내용을 출력한 결과는 다음과 같다.
그림 23. 결과 모습(Java 방식) - XML Mapper - Spring Beans 객체 방식 적용 (Spring 전용)
그림 24. 프로젝트 구성도
34. 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>
35. 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.mapper.CompUsersMapper;
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;
}
}
파일명: SqlSessionFactory.java
[첨부(Attachments)]
36. com.example.spbatis.mapper - CompUsersMapper.java
package com.example.spbatis.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.example.spbatis.model.CompUsers;
@Mapper
public interface CompUsersMapper {
@Select("SELECT * FROM comp_users")
List<CompUsers> selectAll();
}
파일명: CompUsersMapper.java
[첨부(Attachments)]
37. 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.mapper.CompUsersMapper;
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()) {
CompUsersMapper mapper = session.getMapper(CompUsersMapper.class);
user = mapper.selectAll();
// System.out.println("계정명:" + user.getUsername());
}
return user;
}
}
파일명: CompUsersDao.java
[첨부(Attachments)]
38. 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)]
39. 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 home4(Class Mappers) - Java! 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)]
40. 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 - 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)]
* 5부에서 만나요.
1. [Spring-F.] 29. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법5(SqlMap Spring전용) // 결과: 지원, 2020-10-02