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를 통해 똑같은 아이디의 요청이 있는지 확인하고 처리할 빈을 선택해줍니다.

ORM(Object Relation Mapper Framework) - Hibernate 이용




[ hibernate 의 장점 ]

=>ORM: 테이블의 행과 클래스의 객체를 매핑시켜서 데이터베이스를 연동하는 방식

=> SQL 없이 데이터베이스 연동 가능

=>SQL Mapper Framework 인 MyBatis 보다 성능이 우수

[ 사용 전 생각해볼 것 ]

=>spring-orm 과 hibernate 라이브러리가 있어야 합니다.

=>VO 클래스가 반드시 있어야 합니다.

=>VO 클래스와 데이터베이스 테이블을 연결하는 설정 파일이 있어야 합니다.

=>LocalSessionFactoryBean  과 PersistencyExceptionTranslationPostProcessor 클래스의 bean이 필요

=>Transaction을 반드시 적용해야 합니다.

[session과 sessionFactory] 

sessionFactory는 Session 객체를 반환 하는 메소드를 제공한다 

session은  org.hibernate.Session 인터페이스이며, insert, update, delete 

그리고 Transaction, Query, Criteria 를 생성하는 factory 메소드를 제공한다

session은 인터페이스 이기때문에 구현해서 사용해야한다 그렇기에 sessionFactory에서 객체를 반환해서 사용한다. 



[1. 저장소 설정] 

<!-- 저장소 설정 -->

<repositories>

<repository>

<id>codelds</id>

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

</repository>

</repositories>




[ 2.pom.xml 파일에서 의존성 설정 ]



<!-- spring 에서 hibernate와 같은 ORM 프레임워크를 사용하기 위한 라이브러리 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-orm</artifactId>

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

</dependency>


<!-- Hibernate -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-entitymanager</artifactId>

<version>${hibernate.version}</version>

</dependency>


<!-- spring jdbc 의존성 설정을 위한 dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

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

</dependency>

<!--오라클 사용을 위한 의존성 설정-->

<dependency>

<groupId>com.oracle</groupId>

<artifactId>ojdbc6</artifactId>

<version>11.2.0.3</version>

</dependency>




[ 3. 하이버 네이트 매핑 파일 설정 ]



=> resources 디렉토리에 만들면 안되고 java 디렉토리 안에 패키지 안에 생성해야 합니다.


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">




[ 4. primary key 설정 ]


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping package="hibernate.domain">

<class name="DTO  or VO 클래스" table="DB테이블이름">

<!--primary key 설정 -->

<id name="code" column="CODE" />

<!-- primary key를 제외한 나머지 프로퍼티 설정 -->


<!-- name의 setter column은 Db의 컬럼이름 -->

<property name="name" column="NAME" />

<property name="manufactuer" column="MANUFACTURE" />

<property name="price" column="PRICE" />

</class>

</hibernate-mapping>


[5.Hibernate를 이용해서 데이터베이스 작업을 수행할 GoodDao 클래스를 만들고 데이터를 삽입하는 메소드를 구현 ]

=> hibernate를 사용할 때는 SessionFactory를 주입받아서 사용합니다. 


package hibernate.dao;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

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

import org.springframework.stereotype.Repository;


import hibernate.domain.Good;


@Repository

public class GoodDao {

//Hibernate 사용을 위한 참조형 변수 

@Autowired

private SessionFactory sessionFactory;

//데이터를 삽입하는 메소드 

public void insertGood(Good good) {

// sessionFactory 를 통해 세션객체 생성 

Session session = sessionFactory.getCurrentSession();

session.save(good);

}

}



[<!-- 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:@localhost:1521:xe" />

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

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

</bean>


[<!-- 데이터베이스 작업 도중 예외가 발생하면 Spring의 예외로변경해서 발생시키기 위한 설정-->]

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />


[<!-- 하이버네이트 사용을 위한 클래스 -->]

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

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

<!--하이버네이트 매핑주소-->

<property name="mappingResources">

<!-- 여러개 입력이 가능하기 때문에 LIST -->

<list>

<value>dao/good.hbm.xml</value>

</list>

</property>


<!-- 데이터 베이스 종류 --> 

<property name="hibernateProperties">

<value>

<!--다른 데이터베이스 쓰라고 하면 검색해서 사용 -->

hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

</value>

</property>

</bean>


<!--반드시 사용해야하는 트랜잭션 2개-->

<!--하이버네이트 트랜잭션 매니저 객체 만들기   -->

<!--하이버네이트는 트랜잭션을반드시 사용해야합니다. 

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

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

</bean>

<!-- 트랜잭션 사용을 위한 설정을 추가 -->

<tx:annotation-driven/>



<!-- 어노테이션 설정을 스프링 프로젝트에서 사용하기 위한 설정  -->

<context:annotation-config />

<!-- 객체를 자동으로 생성해 줄 패키지 설정  -->

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



1. 인터페이스와 클래스의 차이 

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
hjjavainterface I2{
    public String A();
}
interface I3{
    public String B();
}
class D implements I2, I3{
    public String A(){
        return "A";
    }
    public String B(){
        return "B";
    }
}
public class PolymorphismDemo3 {
    public static void main(String[] args) {
    
        //전체 메소드 사용 가능 
        D obj = new D();
        // I2에 정의된 메소드만 사용가능 
        I2 objI2 = new D();
        //I3에 정의된 메소드만 사용가능 
        I3 objI3 = new D();
         
         //아무 문제가 없다.
        obj.A();
        obj.B();
         
        objI2.A();
        //objI2.B(); 존재하지 않는 메소드 
         
        //objI3.A();
        objI3.B(); 존재하지 않는 메소드 
    }
}
cs



 Hand 인터페이스를 implements한 클래스(Car, Book, Water)가 있다


hand에는 들어올리다, 보다라는 메소드가 있고 이것을 implements한 Car,Book,Water는  전부 구현한 상태이다. 

그리고 인터페이스에 주입하는 클래스의 객체가 어떤 것이냐에 따라 서로다른 역할 을 감당할 수 있다. 

//Car클래스의 메소드와 Hand의 인터페이스를 구현한 메소드 및 인스턴스 변수를 사용할 수 있는 것이다. 

Hand hand = new Car();

그러나 여기서 유의할점은 Hand를 implements한 다른 클래스는 new Car()객체의 메소드는 부를 수 없다 

 Hand hand2 = new Book();

//오류 없는 메소드 

hand2.door();



※ 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


+ Recent posts