AOP 관점지향 프로그래밍 


Aspect Oriented Programming(관점 지향 프로그래밍): 객체 지향 프로그래밍을 보완하는 

개념으로 메소드나 클래스를 관점에 따라 분리시켜서 구현하는 프로그래밍 방법

하나의 메소드에 비지니스 로직을 수행하는 문장과 공통으로 사용하는 문장이 같이 존재할 때 이를 분리해서 구현하기 위한 프로그래밍 방식 

관점지향 프로그래밍이라고 하는데 spring에서는 공통으로 사용하는 문장을 별도의 클래스에 작성해서 분리를 할 수 있는 기능을 제공합니다.

실행될 때 코드를 합쳐서 하나의 proxy 객체를 만들어서 실행합니다. 




**AOP 적용

AOP: 하나의 메소드에 비지니스 로직을 수행하는 문장과 공통으로 사용하는 문장이 같이 존재할 때 이를 분리해서 구현하기 위한 프로그래밍 방식

관점 지향 프로그래밍이라고 하는데 spring에서는 공통으로 사용하는 문장을 별도의 클래스에 작성해서 분리를 할 수 있는 기능을 제공합니다.

실행 될 때 코드를 합쳐서 하나의 proxy 객체를 만들어서 실행합니다.


=>Dao 클래스의 메소드가 호출될 때의 시간을 매일 파일에 기록하는 AOP


1.advice로 사용될 클래스를 생성

=>kr.co.pk.advice.LoggingAdvice


package kr.co.pk.advice;


import java.io.FileOutputStream;

import java.io.PrintWriter;

import java.util.Calendar;


import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.springframework.stereotype.Component;


//객체를 자동으로 생성하기 위한 어노테이션

@Component

//Advice 클래스로 만들기 위한 어노테이션

@Aspect

public class LoggingAdvice {


//advice로 수행될 메소드

//pointcut 작성

//접근지정자는 public 다음 *은 모든 리턴 타입

//kr.co.pk.. 은 kr.co.pk 패키지 안에 있는 모든

//*Dao 는 Dao로 끝나는 클래스 .* 은 메소드 이름이 무엇이든지

//(..)은 매개변수 개수에 상관없이

@Around("execution(public * kr.co.pk..*Dao.*(..))")

public Object invoke(ProceedingJoinPoint joinPoint)

throws Throwable{

//pointcut으로 설정된 메소드가 호출되기 전에 수행할 내용

//메소드 이름 가져오기

String methodName = joinPoint.getSignature().toLongString();

//현재 시간 만들기

Calendar cal = Calendar.getInstance();

java.util.Date date = new java.util.Date(

cal.getTimeInMillis());

//파일에 문자열 기록하기 - 파일이 존재하면 이어쓰기

FileOutputStream fos = 

new FileOutputStream("d:\\log.txt", true);

//문자열을 기록할 수 있는 클래스의 객체 만들기

PrintWriter pw = new PrintWriter(fos);

//파일에 기록

pw.println(methodName + " " + date.toString() + "\n");

pw.flush();

pw.close();

Object obj = joinPoint.proceed();

//pointcut으로 설정된 메소드가 호출 된 후에 수행할 내용

return obj;

}

}


2.pom.xml 파일에 aop를 사용하기 위한 의존성 라이브러리를 추가

<dependency>

<groupId>org.aspectj</groupId>

<artifactId>aspectjweaver</artifactId>

<version>1.8.8</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>${org.springframework-version}</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

<version>${org.springframework-version}</version>

</dependency>


3.servlet-context.xml 파일에 aop 네임스페이스를 추가하고 어노테이션으로 설정한 aop를 사용할 수 있는 태그를 추가

<!-- 어노테이션으로 만든 AOP 적용 -->

<aop:aspectj-autoproxy />



 

1:1 통신이 성공하고 난 후 채팅을 만들 때는 클라이언트가 접속을 하면 각각의 클라이언트를 List에 저장을하고 하나의 클라이언트가 메시지를 보내오면 

그 메시지를 List의 모든 클라이언트에게 전송하는 것입니다.


1. Spring Web Socket을 위한 의존성 

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-websocket</artifactId>

<version>${org.springframework-version}</version>

</dependency>


2. 채팅을 위한 웹 소켓 서버 클래스를 생성 

=> com.seunghoo.na.service.ChatHandler클래스 

=> TextWebSocketHandler을 상속받아야합니다.


package com.seunghoo.na.service;


import java.util.ArrayList;

import java.util.List;


import org.springframework.stereotype.Component;

import org.springframework.web.socket.CloseStatus;

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component

public class ChatHandler extends TextWebSocketHandler {

// 접속한 클라이언트 세션들을 저장할 LIST를 생성

// 이 List는 1개만 만들어져야 하므로 static으로 선언

private static List<WebSocketSession> list = new ArrayList<WebSocketSession>();


//클라이언트가 접속 했을 때 호출될 메소드 

//클라이언트가 접속 했을 때 호출되는 메소드 

@Override

public void afterConnectionEstablished(WebSocketSession session) throws Exception {

list.add(session);

System.out.println("하나의 클라이언트가 연결됨 ");

}

//클라이언트가 메시지를 보냈을 때 호출되는 메소드 

@Override

protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

// 전송된 메시지를 List의 모든 세션에 전송

String msg = message.getPayload();

for (WebSocketSession s : list) {

s.sendMessage(new TextMessage(msg));

}

}


// 클라이언트의 접속이 해제 되었을 때 호출되는 메소드

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

System.out.println("클라이언트와 연결 해제됨");

list.remove(session);

}

}



3. home.jsp 파일에 채팅창으로 이동하는 링크를 추가 

<a href ="chat"> 채팅 </a>


4. HomeController에서 chat 요청이 왔을 때 chat.jsp로 이동하도록 메소드 생성 

@RequestMapping(value = "chat", method = RequestMethod.GET)

public void chat(Locale locale, Model model) {

}


5. ChatHandler클래스를 웹 소켓으로 등록 : Servlet-context.xml 파일 

<websocket:mapping handler="chatHandler" path="/chat-ws"/>

6. views 디렉토리에 채팅페이지(chat.jsp)를 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<div id="one">

별명:<input type="text" id="nickname" /> <input type="button"

id="enter" value="입장" />

</div>

<div id="two" style="display: none">

<input type="button" id="exit" value="퇴장" /><br />

<div id="chatarea" style="width:400px; height:600px; border:1px solid;"></div>

<input type="text" id="message" /> <input type="button" id="send"

value="보내기" />

</div>


</body>

<script>

one = document.getElementById("one");

two = document.getElementById("two");


document.getElementById("enter").addEventListener("click", function() {

//웹 소켓 연결해주는 함수 호출 

connect();

});


document.getElementById("exit").addEventListener("click", function() {

//연결을 해제해주는 함수 호출 

disconnect();

});

document.getElementById("send").addEventListener("click", function() {

//연결을 해제해주는 함수 호출 

send();

});

var websocket;

//입장 버튼을 눌렀을 때 호출되는 함수 

function connect(){

websocket = new WebSocket("ws://localhost:9000/na/chat-ws");

//웹 소켓에 이벤트가 발생했을 때 호출될 함수 등록 

websocket.onopen = onOpen;

websocket.onmessage = onMessage;

websocket.onclose = onClose;

}

//퇴장 버튼을 눌렀을 때 호출되는 함수 

function disconnect(){

msg = document.getElementById("nickname").value;

websocket.send(msg+"님이 퇴장하셨습니다");

websocket.close();

}

//보내기 버튼을 눌렀을 때 호출될 함수 

function send(){

nickname = document.getElementById("nickname").value;

msg = document.getElementById("message").value;

websocket.send(nickname + ":"+ msg);

document.getElementById("message").value = "";

}

//웹 소켓에 연결되었을 때 호출될 함수 

function onOpen(){

nickname = document.getElementById("nickname").value;

websocket.send(nickname + "님 입장하셨습니다.");

}

//웹 소켓에서 연결이 해제 되었을 때 호출될 함수 

function onMessage(evt){

data= evt.data;

chatarea = document.getElementById("chatarea");

chatarea.innerHTML = data + "<br/>" + chatarea.innerHTML

function onClose(){

}

</script>

</html>



*인코딩 

iso-8859-1(iso-lation-1) 기본 인코딩으로 많이 사용 , 한글지원이 안됨 

euc-kr(ms949, cp949) MS가 한글을 지원하기 위해 만든 인코딩 

utf-8 전 세계 모든 글자를 지원하기 위해 만든 인코딩 

최근에는 전부 utf-8로 인코딩합니다.









[ 1. home.jsp 파일에서 파일목록보기를 하면 c:\에 있는 파일들의 목록을 출력하기 ]



<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>홈</title>

</head>

<body>

  <a href="fileview.do"> 파일목록보기</a>

</body>

</html>


2. ViewService인터페이스를 implements한  ViewServiceImpl에서 파일이 존재하면 list에 저장하는 메소드를 구현 


package com.naseunghoo.service;


import java.io.File;

import java.util.ArrayList;

import java.util.List;


import org.springframework.stereotype.Service;




@Service

public class ViewServiceImpl implements ViewService {


//배열이나 List를 리턴하는 경우에 받는 쪽에서 거의 대부분 

//반복문을 시용하기 때문에 null을 리턴하면 안됩니다.

//객체 생성을 먼저해서 데이터가 없는 경웨 size 0가 

//되게 리턴해야 합니다.

@Override

public List<String> filelist() {

List<String> list = new ArrayList<String>();

//파일 목록을 조사할 디렉토리를 File객체로 생성 

File f= new File("c:\\");

//디렉토리 안의 모든 파일 및 디렉토리를 가져오기 

String [] ar = f.list();

//배열의 모든 데이터를 순회해서 .이 없는 것들만 list에 추가 

//위치를 찾아주는 메소드는 데이터가 없으면 음수를 리턴하거나 

//예외를 발생시킵니다. 

for(String imsi : ar) { 

if(imsi.indexOf(".")>=0) {

list.add(imsi);

}

}

return list;

}


}



3. 화면에 출력하기 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>보여주기</title>

</head>

<body>

<table border="1">

<tr><th>파일명</tr>


<c:forEach var="item" items="${list}">

<tr>

<!-- 파라미터 이름  -->

<td><a href="download/${temp}">${temp}</a></td>

</tr>

</c:forEach>

</table>

</body>

</html>



**Web에서 파일 다운로드 

=> web서버에서 파일의 경로만 a href="파일경로"의 형식으로 링크를 걸면 파일을 다운로드 받을 수 있습니다. 

=> 직접 파일 경로를 설정한 경우에는 브라우저가 출력할 수 있는 파일의 경우 

=> 파일을 다운로드 하지 않고 실행을 시킵니다. 

텍스트 파일이나 이미지 파일의 경우는 화면에 출력됩니다.

=> 브라우저가 출력하지 않고 다운로드 하게 만들려면 파일경로에 Controller가 처리할 수 있는 링크를 만들어주고 Controller에서 다운로드하는 

뷰로 출력하도록 설정하면 됩니다 /.


1. fileview.jsp 파일의파일명을 출력하는 부분에 링크를 설정 

<!-- 파라미터 이름  -->

<td><a href="download?filename=${item}">${item}</a></td>


2. homeController에 위의 요청을 처리하는 메소드를 생성 

@RequestMapping(value="download/{}",method=RequestMethod.GET)

public String download(@PathVariable String filename, Model model){

File f= new File("c:\\ + filenaame");

//데이터 저장 

model.addAttribute("file", f);

//출력할 뷰 이름 리턴 

return "download";

}

3. file 이라는 이름으로 넘어온 파일 객체를 가지고 다운로드 화면을 만들어주는 뷰 클래스 생성 

= com.naseunghoo.view.view.DownloadView - AbstractView를 상속 

=> 화면을 직접 만들고자 할 때 AbstractView를 상속 받습니다.


package com.naseunghoo.view.view;


import java.io.File;

import java.io.FileInputStream;

import java.io.OutputStream;

import java.net.URLEncoder;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.util.FileCopyUtils;

import org.springframework.web.servlet.view.AbstractView;


public class DownloadView extends AbstractView {


public DownloadView() {

super();

// 파일의 종류 설정 - 다운로드 받을 수 있도록 설정

setContentType("application/download; charset=utf-8");


}


userAgent 는 유저가 접속하는 브라우져를 알기 위해서 확인 

@Override

//

protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,

HttpServletResponse response) throws Exception {


// Controller에서 넘어온 데이터를 가져오기

// Map에서 데이터를 가져올 때는 반드시 원래의 자료형으로 형변환 해주어야합니다.

// model은 Map의 형태로 자료를 가지고 있고 값은 Object 이기 때문에

// 형변환 해주는 것입니다.

//get의 값은 controller에서 model로 보내는 addAttribute 키값을 적어주면 됩니다.  

File file = (File) model.get("file");

// 응답할 객체의 종류와 크기 설정

response.setContentLength((int) file.length());

response.setContentType(getContentType());


// 접속한 클라이언트의 운영체제 종류와 브라우저 종류를

// 알아 낼 수 있는 헤더 가져오기

String userAgent = request.getHeader("User-Agent");


// 접속한 브라우저가 IE 인지 확인

boolean ie = userAgent.indexOf("rv") > -1;

// 브라우저 별 파일 이름 설정

// 브라우저 별로 한글 인코딩은 다르게 설정됩니다.

// IE와 다른 브라우저로 구분

String filename = "";

if (ie) {

filename = URLEncoder.encode(file.getName(), "utf-8");

} else {

filename = new String(file.getName().getBytes("utf-8"), "iso-8859-1");

}


// 응답 객체에 파일 이름을 설정

response.setHeader("Content-Disposition", "attachment; fulename\"" + filename + "\";");


// 원본 파일의 내용을 읽어서 response를 통해서 전송

OutputStream out = response.getOutputStream();


try (FileInputStream fis = new FileInputStream(file)) {


FileCopyUtils.copy(fis, out);


} catch (Exception e) {

System.out.println("[다운로드] 예외 " + e.getMessage());

e.printStackTrace();

}

}


}



4. servlet-context.xml 파일에 가서 기존 ViewResolver의 우선 순위를 변경하고 beanNameViewResolver를 추가하고 download 뷰 요청이 왔을 때 출력할 뷰를 설정 


1) 출력할 뷰를 설정할 때 기존의 jsp가 아닌 직접 작성한 뷰로 출력할 수 있도록 해주는 

BeanNameViewResolver 클래스의 bean 을 생성 

beanNameViewResolver를 통해 똑같은 아이디의 요청이 있는지 확인하고 처리할 빈을 선택해줍니다.

<beans:bean class="org.springframework.web.servlet.view.BeanNameViewResolver">

<beans:property name="order" value="0"></beans:property>

</beans:bean>


2) 기존 VeiwResolver의 우선 순위를 변경 

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

에 아래 프로퍼티를 추가 

<beans:property name="order" value="1"></beans:property>



3) controller에서 download라는 뷰 이름을 넘겨줄 때 출력할 뷰를 직접 설정 

<beans:bean id="download" class="com.naseunghoo.view.view.DownloadView"></beans:bean>









[다른방법] 

1. 파라미터를 읽어서 수행해야할 경우 home.jsp  파일에  download 링크 파일을 수정  filename이라는 파라미터속성 추가 작성 


<td><a href="download?filename=${temp}">${temp}</a></td>



@RequestMapping(value="download",method=RequestMethod.GET)

public String download(@RequestParam("filename") String filename, Model model){

File f= new File("c:\\ + filename");

//데이터 저장 

model.addAttribute("file", f);

//출력할 뷰 이름 리턴 

return "download";

}

beanNameViewResolver를 통해 똑같은 아이디의 요청이 있는지 확인하고 처리할 빈을 선택해줍니다.



※ MyBatis의 자료형 매핑

number – Integer, Double, Float, Byte, Short, Long, BigDecimal

char, varchar2, clob – String

date – java.sql.Date, java.util.Date

time – java.sql.Time, java.util.Date 

timestamp – java.sql.Timestamp

blob – byte []



1. 의존성 설정 


<repositories>

<repository>

<id>codelds</id>

<url>https://code.lds.org/nexus/content/groups/main-repo</url>

</repository>

</repositories>


<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc6</artifactId>

<version>11.2.0.3</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>${spring-framework.version}</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.4.6</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.3.2</version>

</dependency>





2. mapper 


<?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=“매퍼이름">

<select id="호출할 이름 " resultType="결과 자료형“ 또는 parameterType=“자료형” >

    select 구문

  </select>

<insert id="호출할 이름" parameterType="매개변수 자료형">

INSERT INTO

AddressBook

VALUES (#{프로퍼티이름 또는 키이름})

</insert>

</mapper>



파라미터 설정 - #{이름}

MyBatis는 기본적으로 PreparedStatement 클래스를 이용해서 SQL을 작성하고 실행

파라미터를 ? 대신에 #{이름}으로 작성

파라미터가 1개인 경우는 wrapper 클래스나 String, Date 클래스로 parameterType을 설정하고 이름은 아무것이나 입력해도 됩니다.

파라미터가 여러 개 인 경우는 parameterType을 DTO 나 Map으로 설정

DTO 클래스를 설정한 경우는 프로퍼티(접근자 메소드 – getter) 이름으로 파라미터 이름을 설정해야 합니다.

Map으로 parameterType을 설정한 경우는 키의 이름을 설정해야 합니다.



SqlSessionTemplate 클래스는 SqlSession 클래스를 상속받았기 때문에 SqlSession의 메소드를 그대로 이용하면 됩니다.

sqlSession.insert, delete, update, selectOne, selectList(매퍼이름.id, 매개변수)를 호출하면 됩니다.

매퍼 파일의 sql 구문이 parameter를 받지 않는 경우라면 매개변수는 생략하고 호출이 가능

insert와 delete, update는 영향 받은 행의 개수를 정수로 리턴

selectOne은 설정한 resultType 객체를 리턴

selectList는 설정한 resultType의 List로 리턴

selectOne 메소드는 결과가 2개 이상 나오면 예외를 발생

Map으로 select 구문의 결과를 받는 경우 컬럼 이름이 키가 되고 데이터가 값

오라클의 데이터의 타입이 Number이면 Map에서는 BigDecimal로 저장

Map으로 select 구문의 결과를 받는 경우 키의 이름은 오라클은 모두 대문자 MySQL은 소문자로 저장



3.mybatis 패키지 경로 설정 


<?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>

<typeAliases>

<package name="com.tistory.tstigma"/>

</typeAliases>

</configuration>





4. applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">


<!-- 어노테이션을 사용할 수 있도록하는 설정  -->


<context:annotation-config/>

<context:component-scan base-package="transaction"></context:component-scan>



<!-- DataSource 빈 설정 -->

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">

<property value="oracle.jdbc.driver.OracleDriver" name="driverClassName" />

<property value="jdbc:oracle:thin:@192.168.0.200:1521:xe" name="url" />

<property value="user08" name="username" />

<property value="user08" name="password" />

</bean>

<!-- SqlSessionFactoryBean : MyBatis 설정 정보 -->

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">

<property name="dataSource" ref="dataSource" />

<!--db 내용을 good.xml에 저장 -->

<property value="classpath:mybatis/mappers/good.xml" name="mapperLocations" />

<property value="classpath:mybatis/mybatis-config.xml" name="configLocation" />

</bean>

<!-- 붙었다 떨어졌다는 여기서하고 위에서는 설정 정보만 가지고 잇습니다.  -->

<!-- SqlSessionTemplate: Mybatis 사용 객체  -->

<bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSession" destroy-method="clearCache">

<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />

</bean>

<!-- MyBatis에 트랜잭션을 적용하기 위한 객체  -->

<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<tx:annotation-driven transaction-manager="transactionManager"/> 

</beans>





MyBatis 연동을 mapper 인터페이스 기반으로 변경



=>인터페이스를 생성하고 메소드 위에 Sql을 작성합니다. 

=> DAO 클래스를 만들지 않아도 됩니다. 



1.SQL을 실행할 수 있는 GoodMapper 인터페이스를 생성하고 메소드를 생성 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.tistory.tstigma.dao;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import com.tistory.tstigma.domain.Sawon;
 
public interface SawonMapper {
 
    
//sawon 테이블의 전체 데이터를 가져오는 메소드
    @Select("select * from sawon")
    public List<Sawon> allsawon();
    
    //데이터를 삽입하는 메소드 
    @Insert("insert into sawon values (sawonseq.nextval, #{name},#{email},#{tel},#{address})")
    public void insertsawon(Sawon sawon);
    
    //데이터를 수정하는 메소드 
    @Update("update sawon set name=#{name}, email=#{email}, tel=#{tel}, address=#{address} where bunho=#{bunho}")
    public void updatesawon(Sawon sawon);
    
    //데이터를 삭제하는 메소드
    @Delete("delete sawon where bunho=#{bunho}")
    public void deletesawon(Integer bunho);
    
    //name이 포함된 데이터를 찾아오는 메소드 
    @Select("select * from sawon where lower(trim(name)) like '%' || #{name} || '%'")
    public List<Sawon> getsawon(String name);
}
 
cs


2.application Context.xml 파일에서 myBatis 연동 객체 만드는 부분을 수정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
 
 
 
     <!-- 어노테이션을 프로젝트에서 사용할 수있도록 설정   -->
    <context:annotation-config/>
    
    <!-- 패키지 안에 있는 클래스들 중에서 어노테이션이 붙은 클래스들의 bean을 자동 생성해주는 설정  -->
    <context:component-scan base-package="com.tistory.tstigma"></context:component-scan>
    
    <!-- 데이터 베이스 접속 정보를 저장 DataSource 클래스의 bean -->
    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <!-- 접속할 데이터베이스 종류  -->
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@192.168.0.200:1521:xe"/>
        <property name="username" value="user08"/>
        <property name="password" value="user08"/>
    </bean>
 
 
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id ="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
    </bean>
 
 
    <!-- Sql이 작성되어 있는 인터페이스를 등록 -->
    <bean id="goodMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="com.tistory.tstigmg.dao.SawonMapper"></property>
    </bean>
 
 
    <!-- 실제 mybatis 운영을 위한 클래스의 bean -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
 
    
 
</beans>
cs


3 Main에서 실행 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
 
dao     /*@Autowired*/ 주석처리 
 
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
import com.tistory.tstigma.dao.SawonDao;
import com.tistory.tstigma.dao.SawonMapper;
 
public class Main {
 
    public static void main(String[] args) {
 
        
        GenericXmlApplicationContext context = 
                new GenericXmlApplicationContext(
                        "classpath:applicationContext.xml");
        
        SawonMapper dao = context.getBean(SawonMapper.class);
        
    
        System.out.println(dao.allsawon());
        
        
        /*    
        Sawon sawon = new Sawon();
        sawon.setName("아이린");
        sawon.setEmail("red@naver.com");
        sawon.setTel("010");
        sawon.setAddress("청담동");
        dao.insertsawon(sawon);
    
        //데이터 수정 
        Sawon sawon2 = new Sawon();
        
        sawon2.setBunho(4);
        sawon2.setName("배수지");
        sawon2.setEmail("bae@gmail.com");
        sawon2.setTel("011");
        sawon2.setAddress("광주");
        dao.updatesawon(sawon2);
        
        */
        context.close();
    }
}
cs




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
**xml 기반의 MyBatis 연동을 mapper 인터페이스 기반으로 변경
=>인터페이스를 생성하고 메소드 위에 SQL을 작성합니다.
=>Dao 클래스를 만들지 않아도 됩니다.
 
1.SQL을 실행할 수 있는 GoodMapper 인터페이스를 생성하고 메소드를 생성
package kr.co.pk.dao;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import kr.co.pk.domain.Sawon;
 
public interface SawonMapper {
    //sawon 테이블의 전체 데이터를 가져오는 메소드
    @Select("select * from sawon")
    public List<Sawon> allsawon();
    
    //데이터를 삽입하는 메소드 - 리턴타입 정수
    @Insert("insert into sawon values("
            + "#{bunho}, #{name}, #{email}, #{tel}, #{address}")
    public int insertsawon(Sawon sawon);
    //데이터를 수정하는 메소드 - 리턴타입 정수
    @Update("update sawon "
            + "set name=#{name}, email=#{email}, tel=#{tel}, "
            + "address=#{address} "
            + "where bunho=#{bunho}")
    public int updatesawon(Sawon sawon);
    
    //데이터를 삭제하는 메소드 - 리턴타입 정수
    @Delete("delete from sawon where bunho=#bunho")
    public int deletesawon(Integer bunho);
    
    //name이 포함된 데이터를 찾아오는 메소드
    @Select("select * from sawon where name = '%'||#{name}||'%'")
    public List<Sawon> getsawon(String name);
}
 
2.applicationContext.xml 파일에서 MyBatis 연동 객체 만드는 부분을 수정
    <!-- MyBatis 설정 내용을 저장하고 있는 클래스의 bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- sql이 작성되어 있는 인터페이스를 등록 -->
    <bean id="goodMapper" 
        class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" 
            value="kr.co.pk.dao.SawonMapper" />
    </bean>
 
3.main 메소드에서 테스트
GenericXmlApplicationContext context = 
            new GenericXmlApplicationContext(
                "classpath:applicationContext.xml");
        SawonMapper dao = context.getBean(SawonMapper.class);
        System.out.println(dao.allsawon());
 
cs


'Java > 스프링' 카테고리의 다른 글

파일다운로드 방법  (0) 2018.04.19
mybatis 연결할 때 한번보기 위해 저장  (0) 2018.04.13
스프링 Mybatis를 XML DB 연결  (0) 2018.04.12
JdbcTemplate 클래스  (0) 2018.04.09
Spring 2-2 TEST 디렉토리 사용  (0) 2018.04.09


[ 자바 응용프로그램 개발을 위해 Toad를 이용해 0412Sawon_sql 파일을 만들고 테이블 생성 ]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
--Sawon 테이블 삭제 
drop table sawon ;
 
--일련번호를 만들어 줄 Sequence 생성 
create sequence sawonseq;
 
 
--Sawon 테이블 생성 
create table sawon ( 
bunho number(10primary key,
name varchar2(50),
email varchar2(100),
tel varchar2(12),
address varchar2(100)
);
 
--시퀀스를 이용한 삽입 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '감강찬','kang@gmail.com','01025458874','고려귀주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '김유신','yousin@gmail.com','01058687434','신라거주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '근초고왕','chgo@gmail.com','01021545785','백제거주');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '을지문덕','ul@gmail.com','01025458874','고구려살수');
 
insert into sawon(bunho, name, email, tel, address)
values(sawonseq.nextval, '무열왕','mu@gmail.com','01025458874','신라');
 
--데이터 삽입 확인 
select * from sawon;
 
--address에 신라가 포함된 데이터만 검색 
select * from sawon
where address like '%라';
 
--번호를 가지고 이름과 이메일 전화번호와 주소를 변경 
update sawon
set name='을지문덕', email='ulul@naver.com', tel='01052458774', address='고구려살수'
where bunho=4;
 
--번호를 가지고 삭제 
delete sawon where bunho=4;
 
--데이터베이스에 저장 
commit;
 
rollback
cs



2. Simple Spring Maven Project를 생성 

3. java Version과 Spring Version 변경 


4. 저장소 설정 


1
2
3
4
5
6
<repositories>
    <repository>
        <id>codelds</id>
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
</repositories>
cs


5.의존성 설정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
 
cs


5. 테이블과 연동할 Vo 클래스를 생성 (com.tistory.tstigma.domain.Sawon)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
 
package com.tistory.tstigma.domain;
 
public class Sawon {
 
    private String bunho ;
    private String name ;
    private String email; 
    private String tel;
    private String address;
    public String getBunho() {
        return bunho;
    }
    public void setBunho(String bunho) {
        this.bunho = bunho;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        return "Sawon [bunho=" + bunho + ", name=" + name + ", email=" + email + ", tel=" + tel + ", address=" + address
                + "]";
    }
}
 
cs


[ xml 파일에 sql을 작성할 때 사용하는 MyBatis 환경 설정 파일을 생성 ]

=> src/main/resources 디렉토리에 mybatis-config.xml 

=> VO  클래스들이 모여있는 패키지 이름을 등록해서 mapper파일에서 패키지 이름을 입력하지 않아도 되도록 설정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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>
 
    <typeAliases>
 
        <package name="com.tistory.tstigma" />
 
    </typeAliases>
 
</configuration>
 
cs




7. sql을 작성할 mapper파일을 생성 

=> src/main/resource 디렉토리 안에 mapper 디렉토리를 생성하고 그 안에 sawon.xml 파일로 생성 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?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="sawon">
 
 
 
    <!-- sawon 테이블의 전체 데이터를 가져오는 sql -->
 
    <!-- result Type은 sawon만 써주면 된다 결과 -->
 
    <select resultType="Sawon" id ="AllSawon" >
 
        select bunho, name, email, tel, address 
 
        from sawon; 
 
    </select>
 
 
 
    <!-- sawon 테이블에 데이터를 저장하는 sql  -->
 
    <!-- insert update delete는 결과가 없다.  -->
 
    <!-- parameter는 #같은 반인딩 해줄 때 사용  -->
 
    <insert  parameterType="Sawon" id="insertsawon">
 
            insert into sawon (bunho, name, email, tel, address) 
 
            values(sawonseq.nextval, #{name}, #{email},#{address})
 
    </insert>
 
    
 
    <!-- sawon 테이블에서 bunho를  가지고 일치하는 데이터의 name, email, tel, address를 수정하는 sql  -->
 
    <update id="updatesawon" parameterType="Sawon">
 
        update sawon 
 
        set name=#{name}, email=#{email}, address=#{address}
 
        where bunho=#{bunho}
 
    </update>
 
    
 
    <!-- sawon 테이블에서 bunho를 가지고 삭제하는 sql  -->
 
    <delete id="deletesawon" parameterType="java.lang.Integer">
 
        delete sawon where bunho=#{bunho}
 
    </delete>
 
    
 
    
 
    <!-- 테이블에서 name을 포함한 검색  -->
 
    <!--  굳이 ?  -->
 
    
 
    <select id="getsawon" parameterType="java.lang.String" resultType="Sawon">
 
        select bunho, name, email, tel, address
 
        from sawon
 
        where lower(trim(name)) like '%' || #{name} || '%'
 
    </select>
 
    
 
</mapper>
cs



8. mapper 파일에 있는 Sql 을 호출하는 Dao 클래스를 만들고 메소드를 작성 

=>com.tstigma.tistory.dao.SawonDao



9. 프로젝트에 Spring 설정 파일을 추가하고 bean(spring이 생성해주는 객체 )을 생성하는 코드를 작성 

=> src/ main/resources 디렉토리에 applicationContext.xml


1)context 네임 스페이스 추가 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 
    xmlns:context="http://www.springframework.org/schema/context"
 
    xmlns:tx="http://www.springframework.org/schema/tx"
 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
 
 
 
 
 
 
 
     <!-- 어노테이션을 프로젝트에서 사용할 수있도록 설정   -->
 
    <context:annotation-config/>
 
    
 
    <!-- 패키지 안에 있는 클래스들 중에서 어노테이션이 붙은 클래스들의 bean을 자동 생성해주는 설정  -->
 
    <context:component-scan base-package="com.tistory.tstigma"></context:component-scan>
 
    
 
    <!-- 데이터 베이스 접속 정보를 저장 DataSource 클래스의 bean -->
 
    <bean id="dataSource"
 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
    <!-- 접속할 데이터베이스 종류  -->
 
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
 
        <property name="url" value="jdbc:oracle:thin:@192.168.0.200:1521:xe"/>
 
        <property name="username" value="user08"/>
 
        <property name="password" value="user08"/>
 
    </bean>
 
 
 
    <!-- myBatis 사용을 위한 Bean -->
 
    <!-- 공장이기 때문에 이 팩토리에게 무엇인가 하나더 만들어주세요 요청해야합니다. 
 
    그 주는 것은 아래 실제 운영으 위한 mybatis 클래스의 빈을 추가  -->
 
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id ="sqlSessionFactory">
 
        <property name="dataSource" ref="dataSource"/>
 
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
 
        <property name="mapperLocations" value="classpath:mappers/sawon.xml"/>
 
    </bean>
 
 
 
 
 
    <!-- 실제 mybatis 운영을 위한 클래스의 bean -->
 
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
 
    </bean>
 
 
 
    
 
 
 
</beans>
cs


10. main 메소드를 소유한 Main 클래스를 만들어서 spring 설정 파일의 내용을 읽는 코드를 작성 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        GenericXmlApplicationContext context = 
            new GenericXmlApplicationContext(
                "classpath:applicationContext.xml");
        SawonDao dao = context.getBean(SawonDao.class);
 
 
        //데이터 조회 
        System.out.println(dao.allsawon());
 
        //데이터 수정
        Sawon sawon = new Sawon();
        sawon.setBunho(4);
        sawon.setName("배수지");
        sawon.setEmail("bae@gmail.com");
        sawon.setTel("011");
        sawon.setAddress("광주");
        dao.updatesawon(sawon);
        //문자열을 가지고 조회할 때는 trim() 과 대소문자 변환을 포함
        System.out.println(dao.getsawon("수".toLowerCase()));
cs


JdbcTemplate 클래스


=>Spring JDBC 클래스

=>sql의 매개변수를 Object [] 을 이용해서 매핑하는 클래스



[생성자]

JdbcTemplate(DataSource dataSource)


[select 구문을 수행해주는 메소드]


[select 구문의 결과가 여러 개의 행일 때 사용]


List query(String sql, RowMapper rowMapper)

List query(String sql, Object [] args, RowMapper rowMapper)



[select 구문의 결과가 하나의 행일 때 사용]

Object queryForObject(String sql, RowMapper rowMapper)

Object queryForObject(String sql, Object [] args, RowMapper rowMapper)


[select 구문의 결과가 하나의 행일 때 하나의 Map 에 결과를 저장하고자 하는 경우 사용]

Map<String, Object> queryForMap(String sql)

Map<String, Object> queryForMpa(String sql, Object [] args)


[RowMapper 인터페이스]

=>select 구문의 결과로 반환되는 하나의 행을 객체로 만들기 위한 메소드를 소유한 인터페이스

=>mapRow(ResultSet rs, int rownum) 추상 메소드를 소유

=>rs는 하나의 행을 저장한 객체이고 rownum은 행 번호를 저장한 정수



[JdbcTemplate 클래스를 이용한 테이블의 데이터 읽기]

1.spring-jdbc 라이브러리 다운로드
=>pom.xml 파일에 spring-jdbc 의존성 확인

2.spring 설정 파일(bean configuration 파일 - applicationContext.xml)에 DataSource 빈이 추가되어 있는지 확인




3.샘플 테이블 및 데이터 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
--스쿨버스를 위한 db설계 
-- busnum , name , price , sysdate
 
--시퀀스 생성 
create sequence busnumseq;
 
--테이블 생성 
create table schoolbus(
busnumber number(10primary key,
name varchar2(20not null,
price number(10),
writedate date default sysdate
);
 
--샘플데이터
insert into schoolbus (busnumber, name, price, writedate ) values(busnumseq.nextval, '붕붕카'300, sysdate);
insert into schoolbus (busnumber, name, price, writedate ) values(busnumseq.nextval, '서울카'500, sysdate);
 
--데이터 확인 
select *
from schoolbus;
 
--작업완료 
commit
 
cs


4. JdbcTeplate  클래스의 객체를 소유한 Dao 클래스 생성 dao.schoolbus


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package dao;
 
import java.util.Map;
 
import org.springframework.jdbc.core.JdbcTemplate;
 
public class SchoolBus {
    // Spring JDBC 기본 클래스
    private JdbcTemplate jdbcTemplate;
 
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
 
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    // 데이터의 개수를 알려주는 메소드
    public Map<String, Object> count() {
        // 하나의 행만 리턴하는 select 구문 수행
        return jdbcTemplate.queryForMap("select count(*) from schoolbus");
 
    }
}
 
 
cs


5. spring 설정파일에 SchoolBus 객체를 만들기  

1
2
3
4
5
6
7
8
9
10
11
<bean class="org.springframework.jdbc.core.JdbcTemplate" id = "jdbcTemplate">
        <!--  생성자 주입  -->
        <constructor-arg ref= "dataSource"></constructor-arg>
    </bean>
    
    
    <!-- school 클래스의 객체를 생성 IOC -->
    <bean class ="dao.SchoolBus" id="shcoolbus">
    <!-- jdbcTemplate이라는  id를 가진 bean을 jdbcTemplate 이라는 프로퍼티에 주입 :DI  -->
    <property name="jdbcTemplate" ref ="jdbcTemplate"></property>
    </bean>
cs


6.main 메소드를 소유한 Main 클래스를 만들고 main 메소드 실행


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.context.support.GenericXmlApplicationContext;
 
import dao.SchoolBus;
 
public class Main {
 
    public static void main(String[] args) {
        GenericXmlApplicationContext context = 
            new GenericXmlApplicationContext(
                            "classpath:applicationContext.xml");
        SchoolBus bus = context.getBean(SchoolBus.class);
        //select 절에 쓴 내용을 적기 
        System.out.println(bus.count().get("COUNT(*)"));
    }
 
}
 
cs






Spring 2-2 JUnit 사용 




=>src/test/java 디렉토리에 클래스를 만들면 배포할 때는 사라지는 클래스를 만들 수 있습니다.

=>테스트 하고자 하는 모듈이 있을 때는 src/test/java 디렉토리에 클래스를 하나 만들고 그 클래스 안에 @Test라는 어노테이션과 함께 메소드를 만들면 테스트 가능한 메소드를 만들어서 테스트 할 수 있습니다.


1.Simple Spring Maven Project를 생성


2.Java 버전 변경

1)프로젝트를 선택하고 마우스 오른쪽을 클릭해서 [Properties]를 실행하고 Project Facets에서 버전 변경


2)pom.xml 파일에서 java version 변경

<java.version>1.8</java.version>


3.pom.xml 파일에서 Spring Version 변경

4.2.4, 4.1.0, 4.0.4, 4.0.1 등으로 변경


<spring-framework.version>4.2.4.RELEASE</spring-framework.version>


4.pom.xml 파일에 오라클 사용을 위한 의존성 라이브러리 설정을 추가

1)오라클은 중앙 저장소에서 다운로드 받을 수 없어서 repositories를 설정해야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 라이브러리 다운로드 받을 저장소 설정 -->
 
<repositories>
 
    <repository>
 
        <id>codelds</id>
 
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
 
    </repository>
 
</repositories>
cs


2)오라클 라이브러리 다운로드 코드를 <dependencies> 태그 안에 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 오라클 라이브러리 의존성 설정 -->
 
<dependency>
 
    <groupId>com.oracle</groupId>
 
    <artifactId>ojdbc6</artifactId>
 
    <version>11.2.0.3</version>
 
</dependency>
 
 
cs


5. src/test/java 에 테스트 용으로 사용할 클래스를 생성 : ConnectionTest


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
import org.junit.Test;
 
public class ConnectionTest {
 
    // 테스트를 수행할 메소드
    @Test
    public void connect() {
        // 1. 데이터 베이스 연동 클래스 로드
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
 
        } catch (ClassNotFoundException e) {
            // 이 메시지가 출력되면 드라이버 클래스 이름을 잘못 했거나
            // 라이브러리가 다운로드 되지 않은 경우입니다.
            System.out.println("[TEST] DB 연결 " + e.getMessage());
            e.printStackTrace();
        }
 
        // 2. 데이터 베이스 연결
        // try() 안에 연결하면 해제 할 필요가 없습니다.
        // 이 문법은 java1.7 이상에서 사용이 가능합니다.
        try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.200:1521:xe"
                "user08","user08")) {
        } catch (SQLException e) {
            System.out.println("[연결]" + e.getMessage());
            e.printStackTrace();
        }
 
    }
}
cs


'Java > 스프링' 카테고리의 다른 글

스프링 Mybatis를 XML DB 연결  (0) 2018.04.12
JdbcTemplate 클래스  (0) 2018.04.09
Spring 2-1 Property(속성)  (0) 2018.04.09
Spring 1- 2 DI와 IOC ,@Component @Bean 사용 정리  (0) 2018.04.06
DI(Dependency Injection)  (0) 2018.04.05

+ Recent posts