고인돌 프로젝트/[Step 4] Spring boot + Oracle

3. Spring boot + mybatis + logback-spring

고인돌개발자 2021. 8. 29. 21:37

참고, Step 1,2,3 진행 후 , DB 연결부분에 대한 학습입니다.


1. 패키지 구조, 디렉토리 구조 추가 

   - mybatis 패키지 아래로 controller, service, dao 패키지 추가
      - vo 패키지는 com.model2.spring 바로 아래 추가 
   - xml 매퍼 
   - logback-spring.xml
   - WEB-INF > view > list.jsp , list_id.jsp (기존 소스 일부 수정하여 사용)
   - webapp > index.html  | webapp > jsp> regist.jsp ( mapping 위치를 파라메터로 받아서 처리 하도록 ) 

 

<project - package 구조>


2. 환경세팅 (pom.xml , application.properties , logback-spring.xml)

 

더보기

src/main/resources/application.properties

# change port
# server.port = 8084

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

#oracle settings for jdbctemplate
#spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=scott
spring.datasource.password=tiger

#mybatis
mybatis.mapper-locations=classpath:mybatis/mapper/**/**.xml

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.model2</groupId>
	<artifactId>Model2_Spring_War</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>Model2_Spring_War</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<scope>runtime</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
		<dependency>
		    <groupId>org.apache.tomcat.embed</groupId>
		    <artifactId>tomcat-embed-jasper</artifactId>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <scope>provided</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>2.2.0</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

src/main/resources/logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>[%d{yyyy-MM-dd HH:mm:ss}:%-3relative] [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>
    </appender>

    <logger name="com.model2.spring" level="debug"/>

    <root level="off">
        <appender-ref ref="console"/>
    </root>
</configuration>

 


3. 소스코드 - jdbcTemplate 패키지 하위

 

더보기

com/model2/spring/mybatis/controller/Con_mbt_People.java

package com.model2.spring.mybatis.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model2.spring.mybatis.service.Sv_mbt_IfPeople;
import com.model2.spring.vo.Vo_People;

@Controller
@RequestMapping("/mybatis")
public class Con_mbt_People {
	
	Sv_mbt_IfPeople sv_People;
	
	/* 생성자를 통한 Di */
	@Autowired
	public Con_mbt_People(Sv_mbt_IfPeople sv_People) {
		this.sv_People = sv_People;
	}
	
	
	/* People 의 값을 전부 가져오는 메서드 */
	@RequestMapping("/PeopleList")
	public String getPeopleList(Model model) {
		
		System.out.println("Hi Spring - mybatis -  getPeopleList - Model2_Spring_War");	
		
		List<Vo_People> list = new ArrayList<>();
	    
		list = sv_People.doReadList();
	   	
		System.out.println("2. list size"+ list.size());	
		// 리스트의 값을 Attribute 를 통해 주고 받는다.
		//request.setAttribute("people", list);
		model.addAttribute("people",list);
		model.addAttribute("path","mybatis");
		
		return "jdbc/list";
		//return "/WEB-INF/view/list.jsp";	
	}
	
	/* 특정 ID 값을 져오는 메서드 */
	@RequestMapping("/PeopleId")
	public String getPeopleId(HttpServletRequest request, Model model) {
		
		System.out.println("Hi Spring -  mybatis -  getPeopleId - Model2_Spring_War");	
		
	    String strId = request.getParameter("id");		
		Vo_People vo_People = sv_People.doReadId(strId);
	    
		model.addAttribute("vo_people",vo_People);
		model.addAttribute("path","mybatis");
		
		return "jdbc/list_id";
		//return "/WEB-INF/view/list.jsp";	
	}	
	
	/* ID 를 생성하는 메서드 */
	@RequestMapping("/PeopleCreate")
	public String getPeopleCreate(@ModelAttribute Vo_People vo_People) {
		
		System.out.println("Hi Spring -  mybatis - getPeopleCreate - Model2_Spring_War");	
		
		int int_result = sv_People.doCreate(vo_People.getId(), vo_People.getName(), vo_People.getAge());
	    
		return "redirect:/mybatis/PeopleList";
		//return "/WEB-INF/view/list.jsp";	
	}	

	
	/* ID 를 수정하는 메서드 */
	@RequestMapping("/PeopleUpdate")
	public String getPeopleUpdate(@ModelAttribute Vo_People vo_People) {
		
		System.out.println("Hi Spring -  mybatis - getPeopleUpdate - Model2_Spring_War");	
				
		int int_result = sv_People.doUpdate(vo_People);
		
		return "redirect:/mybatis/PeopleList";
		//return "/WEB-INF/view/list.jsp";	
	}
	
	/* ID 를 삭제하는 메서드 */
	@RequestMapping("/PeopleDelete")
	public String getPeopleDelete(HttpServletRequest request) {
		
		System.out.println("Hi Spring -  mybatis - getPeopleDelete - Model2_Spring_War");	
		
		String strId = request.getParameter("id");	
		int int_result = sv_People.doDelete(strId);
		
		return "redirect:/mybatis/PeopleList";
	}	
}

 

com/model2/spring/mybatis/dao/Dao_If_People.java

package com.model2.spring.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.model2.spring.vo.Vo_People;

/**
 * @author 
 * Mybatis xml 을 호출하는 매퍼 인터페이스 
 * xml - mybatis/mapper/mapper_People.xml
 */
@Mapper
public interface Dao_If_People {

	   // 전체 리스트 가져오기 
		public List<Vo_People> doReadList();
		
		// 특정 Id 리스트만 가져오기 
		public Vo_People doReadId(String id);
		
		// 데이타 로우 생성하기
		public int doCreate(String id, String name, String age);
		
		// 특정 ID 정보 수정하기 
		public int doUpdate(Vo_People vo_People);
		
		// 특정 ID 정보 삭제하기 
		public int doDelete(String id);	
}

 

 com/model2/spring/mybatis/service/Sv_mbt_IfPeople.java

package com.model2.spring.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.model2.spring.vo.Vo_People;

/**
 * @author 
 * Mybatis xml 을 호출하는 매퍼 인터페이스 
 * xml - mybatis/mapper/mapper_People.xml
 */
@Mapper
public interface Dao_If_People {

	   // 전체 리스트 가져오기 
		public List<Vo_People> doReadList();
		
		// 특정 Id 리스트만 가져오기 
		public Vo_People doReadId(String id);
		
		// 데이타 로우 생성하기
		public int doCreate(String id, String name, String age);
		
		// 특정 ID 정보 수정하기 
		public int doUpdate(Vo_People vo_People);
		
		// 특정 ID 정보 삭제하기 
		public int doDelete(String id);	
}

 

 com/model2/spring/mybatis/service/Sv_mbt_People.java

package com.model2.spring.mybatis.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.model2.spring.mybatis.dao.Dao_If_People;
import com.model2.spring.vo.Vo_People;

@Service
public class Sv_mbt_People implements Sv_mbt_IfPeople {
	
	Dao_If_People dao_People;
	
	@Autowired
	public Sv_mbt_People(Dao_If_People dao_People) {
		this.dao_People = dao_People;
	}

	/* People 의 값을 전부 가져오는 메서드 */
	@Override
	public List<Vo_People> doReadList() {
		
		List<Vo_People> list = dao_People.doReadList();
		
		return list;
	}

	/* 특정 ID 값을 져오는 메서드 */
	@Override
	public Vo_People doReadId(String id) {
		
	  Vo_People vo_People =null;	
	  
	  /* data 유효성 검증 */
	  if(id != null) {	
		vo_People = dao_People.doReadId(id);
	  }else {
		vo_People = null;  
	  }
	  
		return vo_People;
	}

	/* ID 를 생성하는 메서드 */
	@Override
	public int doCreate(String id, String name, String age) {
		
		int intI = dao_People.doCreate(id, name, age);
		
		return intI;
	}

	/* ID 를 수정하는 메서드 */
	@Override
	public int doUpdate(Vo_People vo_People) {
		
		int intI = dao_People.doUpdate(vo_People);
		
		return intI;
	}

	/* ID 를 삭제하는 메서드 */
	@Override
	public int doDelete(String id) {

		int intI = dao_People.doDelete(id);
		
		return intI;
	}

}

 

com/model2/spring/vo/Vo_People.java

package com.model2.spring.vo;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/* People DB 에서 값을 받아 저장하고, View 에 던져주는 매개체 역할을 합니다. */

@Getter
@Setter
@ToString
@AllArgsConstructor // 멤버변수를 사용하는 생성자
@NoArgsConstructor  // 기본 생성자 
public class Vo_People {
	
	private String id;
	private String name;
	private String age;
	private String dati;

	}

 

 


4. xml - mapper

 

더보기

src/main/resources/mybatis/mapper/mapper_People.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.model2.spring.mybatis.dao.Dao_If_People"> 
    
    <select id="doReadList" resultType="com.model2.spring.vo.Vo_People">
         select id, name, age, to_char(reg_date,'yyyy.mm.dd') as dati
		  from people
		  order by id
    </select>

    <select id="doReadId" resultType="com.model2.spring.vo.Vo_People">
        select id, name, age, to_char(reg_date,'yyyy.mm.dd') as dati 
			from people
			where id = #{param1}
    </select>

    <insert id="doCreate">
        Insert into people(id, name, age)
		 values (#{param1} , #{param2}, to_number(#{param3}))
    </insert>

    <update id="doUpdate" parameterType="com.model2.spring.vo.Vo_People">
        Update people 
		SET name = #{name} , age = to_number(#{age})
		WHERE id = #{id}        
    </update>
    
    <delete id="doDelete">
    	Delete from people 
		WHERE id = #{param1}
    </delete>
    
</mapper>

5. 소스코드 - html, jsp

 

더보기

src/main/webapp/index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1> ■모델 2 Spring </h1>

 <a href="./jsp/regist.jsp?path=mybatis">● 등록 </a>
 <p>
 <a href="/mybatis/PeopleList">● 조회 (삭제)</a>
   
</body>
</html>

src/main/webapp/jsp/regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	String strPath = request.getParameter("path");
	
%>
    
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> ■모델 2 Spring boot - <%=strPath %> </h1>

 <a href="/index.html">● Home </a>
 <p>
  
 <form name="regist" action="/<%=strPath %>/PeopleCreate" method="post"> 
	<table style="width: 200px;">
		<tr>
			<td> 구분 </td> <td align="center">입력</td> 
		</tr>
		<tr>	
			<td> ID </td>   <td><input type="text" name="id" value="" />   </td> 
		</tr>
		<tr>
			<td> Name </td> <td><input type="text" name="name" value="" /></td> 
		</tr>
		<tr>	
			<td> Age </td>  <td><input type="text" name="age" value="" />  </td> 
		</tr> 
	</table>
	<p>
	<input type="submit"  value="전송" style="width:200px;"> 

 </form>
</body>
</html>

src/main/webapp/WEB-INF/view/jdbc/list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ page import="java.util.*, com.model2.spring.vo.*" %>


<%		
    String strPath = (String)request.getAttribute("path");
	out.println("strPath =>"+strPath);
	List<Vo_People> list2 = (ArrayList<Vo_People>)request.getAttribute("people");	
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select </title>
</head>
<body>


<h1> ■모델 2 , Spring boot - jdbc/list.jsp</h1>

 <a href="/index.html">● Home </a>
 <p>
 
 <table style="width: 400px;" border="0">
		<tr style="height: 40px">
			<td>ID</td>
			<td align="center">이름</td>
			<td align="center">나이</td>
			<td align="center">등록일자</td>			
			<td> 삭제 </td>
		</tr>
		
	<%
			String strId;
	
	try{
			for(Vo_People p : list2){
				strId = p.getId();	
			%>	
				<tr style="height: 40px">
				<td><a href="/<%=strPath %>/PeopleId?id=<%=strId%>"><%=strId%></a></td>
				<td align="center"><%=p.getName()%></td>
				<td align="center"><%=p.getAge()%></td>
				<td align="center"><%=p.getDati()%></td>
				<td><a href="/<%=strPath %>/PeopleDelete?id=<%=strId%>">삭제 </a></td>
			</tr>	
			<%			
			}
				
	  }catch (Exception e) {
			System.out.println("Error =>"+e);			
		 }finally {			
		}	
		
	%>	
		
		
	</table>

</body>
</html>

src/main/webapp/WEB-INF/view/jdbc/list_id.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ page import="java.util.*, com.model2.spring.vo.*" %>


<%	
	String strPath = (String)request.getAttribute("path");	
    Vo_People vo_People = (Vo_People)request.getAttribute("vo_people");	
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select </title>
</head>
<body>


<h1> ■모델 2 , Spring boot - jdbc/list_id.jsp</h1>

 <a href="/index.html">● Home </a>
 <p>

 <form name="regist" action="/<%=strPath %>/PeopleUpdate" method="post">  
 <table style="width: 400px;" border="0">
		<tr style="height: 40px">
			<td> ID </td>   <td><%=vo_People.getId() %><input type="hidden" name="id" value="<%=vo_People.getId() %>" />   </td> 
		</tr>
		<tr style="height: 40px">
			<td> Name </td> <td><input type="text" name="name" value="<%=vo_People.getName() %>" /></td> 
		</tr>
		<tr style="height: 40px">
			<td> Age </td>  <td><input type="text" name="age" value="<%=vo_People.getAge() %>" />  </td> 
		</tr>		
	</table>
<input type="submit"  value="수정" style="width:200px;"> 	
</form>
</body>
</html>

'고인돌 프로젝트 > [Step 4] Spring boot + Oracle' 카테고리의 다른 글

2. Spring boot + JdbcTemplate  (0) 2021.08.25
1. Simple Jdbc  (0) 2021.08.25