Spring & JDBC

문이빈·2023년 9월 15일
0

숙제

값을 입력해도 갯수는 증가하지만 값이 덮어씌여진다. -> singleton 때문에 (주소값 1개)
그래서 입력하여 보내는 주소 값을 다르게 해줘야한다.

----------------------------HelloSpring.java----------------------------

package sample04;

import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {
	
	public void menu(ApplicationContext applicationContext) {		
		  Scanner scan = new Scanner(System.in);
	      SungJuk sungJuk = null;
	      int num;
	      
	      while(true) {
	      System.out.println("***********");
	      System.out.println("  1. 입력");
	      System.out.println("  2. 출력");
	      System.out.println("  3. 수정");
	      System.out.println("  4. 삭제");
	      System.out.println("  5. 끝");
	      System.out.println("***********");
	      System.out.print("번호 입력 : ");
	      num = scan.nextInt();
	      
	      System.out.println();
	      
	      
	         if(num == 5) {
	            break;
	         }else if(num == 1) {
				sungJuk = (SungJuk) applicationContext.getBean("sungJukInput"); // 부모 = 자식
			 }else if(num == 2) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukOutput"); // 부모 = 자식
			 }else if(num == 3) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukUpdate"); // 부모 = 자식
			 }else if(num == 4) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukDelete"); // 부모 = 자식
			}
	         sungJuk.execute();
		}//while
		
	}

	public static void main(String[] args) {
		
		// HelloSpring helloSpring  = new HelloSpring(); 
		// helloSpring.menu();
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); // - 사용하여 연결하고
		HelloSpring helloSpring = applicationContext.getBean("helloSpring", HelloSpring.class); // - 불러고
		helloSpring.menu(applicationContext);
		System.out.println("프로그램을 종료합니다.");
	}
}

----------------------------SungJukDTO2.java----------------------------

package sample04;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter

public class SungJukDTO2 {
	
	private String name;
	private int kor;
	private int eng;
	private int math;
	private int tot;
	private double avg;
	
	@Override
	public String toString() {
		
		return name + "\t"+ kor +"\t"+ eng +"\t"+ math +"\t"+ tot +"\t"+ String.format("%.2f", avg) ;
	}

}

----------------------------SungJukInput.java----------------------------

package sample04;

import java.util.List;
import java.util.Scanner;

import lombok.Setter;

public class SungJukInput implements SungJuk {
	
	@Setter
	private SungJukDTO2 sungJukDTO2;
	@Setter
	private List<SungJukDTO2> list;
	
	/* @Setter로 대신함
	 * 
	 * // setter를 통해서 값을 얻자 
	 * public void setSungJukDTO2(SungJukDTO2 sungJukDTO2) {
	 * 		this.sungJukDTO2 = sungJukDTO2; 
	 * }
	 * 
	 * public void setList(List<SungJukDTO2> list) {
	 *  	this.list = list; 
	 * }
	 */
	  
	@Override
	public void execute() {
	
		Scanner scan = new Scanner(System.in);
		
		System.out.print("이름 입력 : ");
		String name = scan.next();
		System.out.print("국어점수 입력 : ");
		int kor = scan.nextInt();
		System.out.print("영어점수  입력 : ");
		int eng = scan.nextInt();
		System.out.print("수학점수  입력 : ");
		int math = scan.nextInt();
		
		System.out.println();
		
	
		
		int tot = kor + eng + math;
		double avg = tot/3.0;
		
		// SungJukDTO2 sungJukDTO2 = new SungJukDTO2(); 안할거야 application으로 가자
		
		sungJukDTO2.setName(name);
		sungJukDTO2.setKor(kor);
		sungJukDTO2.setEng(eng);
		sungJukDTO2.setMath(math);
		sungJukDTO2.setTot(tot);
		sungJukDTO2.setAvg(avg);
		
		// List<SungJukDTO2> list = new ArrayList<SungJukDTO2>();
		list.add(sungJukDTO2);	
		
		System.out.println(name +"님의 데이터를 입력 하였습니다");
		System.out.println(list);
		
	}

}

----------------------------SungJukOutput.java----------------------------

package sample04;

import java.util.List;

import lombok.Setter;

public class SungJukOutput implements SungJuk {
	
	@Setter
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		System.out.println("이름"+"\t"+"국어"+"\t"+"영어"+"\t"+"수학"+"\t"+"총점"+"\t"+"평균");
		for (SungJukDTO2 sungJukDTO2 : list) {
			System.out.println(sungJukDTO2);
			}
		
		}

	}

----------------------------SungJukUpdate.java----------------------------

package sample04;

import java.util.List;
import java.util.Scanner;

import lombok.Setter;

public class SungJukUpdate implements SungJuk {
	
	@Setter
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("수정할 이름 입력 : ");
		String name = scan.next();
		System.out.println();
		

		int sw=0;
		for(SungJukDTO2 sungJukDTO2 : list) {
			if(sungJukDTO2.getName().equals(name)) {
				sw=1;
				
				System.out.println("이름"+"\t"+"국어"+"\t"+"영어"+"\t"+"수학"+"\t"+"총점"+"\t"+"평균");
				System.out.println(sungJukDTO2);
				
				System.out.print("국어점수 입력 : ");
				int kor = scan.nextInt();
				System.out.print("영어점수  입력 : ");
				int eng = scan.nextInt();
				System.out.print("수학점수  입력 : ");
				int math = scan.nextInt();
				
				System.out.println();
				
				int tot = kor + eng + math;
				double avg = tot/3.0;
				
				sungJukDTO2.setName(name);
				sungJukDTO2.setKor(kor);
				sungJukDTO2.setEng(eng);
				sungJukDTO2.setMath(math);
				sungJukDTO2.setTot(tot);
				sungJukDTO2.setAvg(avg);
				
				System.out.println(name +"님의 데이터를 수정 하였습니다");
				
				break;
			}
		} //for
		
		if(sw==0) {
			System.out.println("찾고자하는 이름이 없습니다");
			return; // 메소드를 벗어나라 -> HelloSpring 으로 나감
		}
	}
}

----------------------------SungJukDelete.java----------------------------

package sample04;

import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import lombok.Setter;


public class SungJukDelete implements SungJuk {
	
	@Setter
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("삭제할 이름 입력 : ");
		String name = scan.next();
		System.out.println();
		
		Iterator<SungJukDTO2> it = list.iterator();
		
		int sw =0;
		while(it.hasNext()) { // 항목이 이으면 true, 없으면 false
			
			// it가 가리키는 항목을 꺼내서 저장한 후, it는 다음 항목으로 이동한다.
			SungJukDTO2 sungJukDTO2 = it.next();
			
			if(sungJukDTO2.getName().equals(name)) {
				sw = 1;
				it.remove(); // 아까 보관한 항목을 제거
				System.out.print(name+"님의 데이터를 삭제 하였습니다");
				
				break;
			}
		}//while
		
		if(sw==0) {
			System.out.println("찾고자하는 이름이 없습니다");
		}//for
	}
}

----------------------------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"
	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.3.xsd">

<!-- sample04 -->
<bean id="helloSpring" class="sample04.HelloSpring"/>

<bean id="sungJukDTO2" class="sample04.SungJukDTO2" scope="prototype"/>

<bean id="sungJukInput" class="sample04.SungJukInput" scope="prototype">
	<property name="sungJukDTO2" ref="sungJukDTO2"/>
	<property name="list" ref="arrayList"/>
</bean>

<bean id="arrayList" class="java.util.ArrayList"/>

<bean id="sungJukOutput" class="sample04.SungJukOutput">
	<property name="list" ref="arrayList"/>
</bean>

<bean id="sungJukUpdate" class="sample04.SungJukUpdate">
	<property name="list" ref="arrayList"/>
</bean>

<bean id="sungJukDelete" class="sample04.SungJukDelete">
	<property name="list" ref="arrayList"/>
</bean>

</beans>

property = setter

Annotation으로 변환

----------------------------SpringConfiguration.java----------------------------

@Bean
	//public ArrayList<SungJukDTO2> arrayList(){ 둘다 상관없음
	  public List<SungJukDTO2> arrayList(){
		return new ArrayList<SungJukDTO2>();
	}
    
----------------------------HelloSpring.java----------------------------

package sample04;

import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class HelloSpring {
	
	public void menu(ApplicationContext applicationContext) {		
		  Scanner scan = new Scanner(System.in);
	      SungJuk sungJuk = null;
	      int num;
	      
	      while(true) {
	      System.out.println("***********");
	      System.out.println("  1. 입력");
	      System.out.println("  2. 출력");
	      System.out.println("  3. 수정");
	      System.out.println("  4. 삭제");
	      System.out.println("  5. 끝");
	      System.out.println("***********");
	      System.out.print("번호 입력 : ");
	      num = scan.nextInt();
	      
	      System.out.println();
	      
	      
	         if(num == 5) {
	            break;
	         }else if(num == 1) {
				sungJuk = (SungJuk) applicationContext.getBean("sungJukInput"); // 부모 = 자식
			 }else if(num == 2) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukOutput"); // 부모 = 자식
			 }else if(num == 3) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukUpdate"); // 부모 = 자식
			 }else if(num == 4) {
				 sungJuk = (SungJuk) applicationContext.getBean("sungJukDelete"); // 부모 = 자식
			}
	         sungJuk.execute();
		}//while
		
	}

	public static void main(String[] args) {
		
		// HelloSpring helloSpring  = new HelloSpring(); 
		// helloSpring.menu();
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); // - 사용하여 연결하고
		HelloSpring helloSpring = applicationContext.getBean("helloSpring", HelloSpring.class); // - 불러고
		helloSpring.menu(applicationContext);
		System.out.println("프로그램을 종료합니다.");
	}
}

----------------------------SungJukDTO2.java----------------------------

package sample04;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Component
@Scope("prototype")

public class SungJukDTO2 {
	
	private String name;
	private int kor;
	private int eng;
	private int math;
	private int tot;
	private double avg;
	
	@Override
	public String toString() {
		
		return name + "\t"+ kor +"\t"+ eng +"\t"+ math +"\t"+ tot +"\t"+ String.format("%.2f", avg) ;
	}

}

----------------------------SungJukInput.java----------------------------

package sample04;

import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class SungJukInput implements SungJuk {
	// 생성된 빈들중에서 SunJukDTO2를 찾아서 자동으로 매핑을 해라
	// 생성자 이건, Setter메소드 이건 상관없이 SunJukDTO2를 찾아서 매핑을 해라
	
	@Autowired
	private SungJukDTO2 sungJukDTO2;
	
	@Autowired
	@Qualifier("arrayList")
	private List<SungJukDTO2> list;
	
	/* @Setter로 대신함
	 * 
	 * // setter를 통해서 값을 얻자 
	 * public void setSungJukDTO2(SungJukDTO2 sungJukDTO2) {
	 * 		this.sungJukDTO2 = sungJukDTO2; 
	 * }
	 * 
	 * public void setList(List<SungJukDTO2> list) {
	 *  	this.list = list; 
	 * }
	 */
	  
	@Override
	public void execute() {
	
		Scanner scan = new Scanner(System.in);
		
		System.out.print("이름 입력 : ");
		String name = scan.next();
		System.out.print("국어점수 입력 : ");
		int kor = scan.nextInt();
		System.out.print("영어점수  입력 : ");
		int eng = scan.nextInt();
		System.out.print("수학점수  입력 : ");
		int math = scan.nextInt();
		
		System.out.println();
		
		int tot = kor + eng + math;
		double avg = tot/3.0;
		
		// SungJukDTO2 sungJukDTO2 = new SungJukDTO2(); 안할거야 application으로 가자
		
		sungJukDTO2.setName(name);
		sungJukDTO2.setKor(kor);
		sungJukDTO2.setEng(eng);
		sungJukDTO2.setMath(math);
		sungJukDTO2.setTot(tot);
		sungJukDTO2.setAvg(avg);
		
		// List<SungJukDTO2> list = new ArrayList<SungJukDTO2>();
		list.add(sungJukDTO2);	
		
		System.out.println(name +"님의 데이터를 입력 하였습니다");
		System.out.println(list);
		
	}

}

----------------------------SungJukOutput.java----------------------------

package sample04;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class SungJukOutput implements SungJuk {
	
	@Autowired
	@Qualifier("arrayList")
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		System.out.println("이름"+"\t"+"국어"+"\t"+"영어"+"\t"+"수학"+"\t"+"총점"+"\t"+"평균");
		for (SungJukDTO2 sungJukDTO2 : list) {
			System.out.println(sungJukDTO2);
			}
		
		}

	}

----------------------------SungJukUpdate.java----------------------------

package sample04;

import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


@Component
public class SungJukUpdate implements SungJuk {
	
	@Autowired
	@Qualifier("arrayList")
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("수정할 이름 입력 : ");
		String name = scan.next();
		System.out.println();
		

		int sw=0;
		for(SungJukDTO2 sungJukDTO2 : list) {
			if(sungJukDTO2.getName().equals(name)) {
				sw=1;
				
				System.out.println("이름"+"\t"+"국어"+"\t"+"영어"+"\t"+"수학"+"\t"+"총점"+"\t"+"평균");
				System.out.println(sungJukDTO2);
				
				System.out.print("국어점수 입력 : ");
				int kor = scan.nextInt();
				System.out.print("영어점수  입력 : ");
				int eng = scan.nextInt();
				System.out.print("수학점수  입력 : ");
				int math = scan.nextInt();
				
				System.out.println();
				
				int tot = kor + eng + math;
				double avg = tot/3.0;
				
				sungJukDTO2.setName(name);
				sungJukDTO2.setKor(kor);
				sungJukDTO2.setEng(eng);
				sungJukDTO2.setMath(math);
				sungJukDTO2.setTot(tot);
				sungJukDTO2.setAvg(avg);
				
				System.out.println(name +"님의 데이터를 수정 하였습니다");
				
				break;
			}
		} //for
		
		if(sw==0) {
			System.out.println("찾고자하는 이름이 없습니다");
			return; // 메소드를 벗어나라 -> HelloSpring 으로 나감
		}

	}

}

----------------------------SungJukDelete.java----------------------------

package sample04;

import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class SungJukDelete implements SungJuk {
	
	@Autowired
	@Qualifier("arrayList")
	private List<SungJukDTO2> list;

	@Override
	public void execute() {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("삭제할 이름 입력 : ");
		String name = scan.next();
		System.out.println();
		
		Iterator<SungJukDTO2> it = list.iterator();
		
		int sw =0;
		while(it.hasNext()) { // 항목이 이으면 true, 없으면 false
			
			// it가 가리키는 항목을 꺼내서 저장한 후, it는 다음 항목으로 이동한다.
			SungJukDTO2 sungJukDTO2 = it.next();
			
			if(sungJukDTO2.getName().equals(name)) {
				sw = 1;
				it.remove(); // 아까 보관한 항목을 제거
				System.out.println(name+"님의 데이터를 삭제 하였습니다");
				
				break;
			}
		}//while
		
		if(sw==0) {
			System.out.println("찾고자하는 이름이 없습니다");
		}//for
	}
}

----------------------------applicationContext.xml----------------------------

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

순서

----------------------------HelloSpring.java---------------------------

package sample05;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {

	public static void main(String[] args) {
		System.out.println("*** Life Cylcle ***");
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

	}

}

----------------------------MessageBeanImpl.java---------------------------

package sample05;

public class MessageBeanImpl implements MessageBean {
	
	private String name; // 생성자
	private String phone;// setter
	private Outputter outputter;
	
	public MessageBeanImpl() {
		System.out.println("MessageBeanImpl 기본생성자");
	}

	public MessageBeanImpl(String name) {
		System.out.println("public MessageBeanImpl(String name)");
		this.name = name;
	}
	
	public void setPhone(String phone) {
		System.out.println("public void setPhone(String phone)");
		this.phone = phone;
	}
	public void setOutputter(Outputter outputter) {
		System.out.println("public void setOutputter(Outputter outputter)");
		this.outputter = outputter;
	}

	@Override
	public void helloCall() {
		
	}

}

----------------------------FileOutputter.java---------------------------

package sample05;

// 파일을 출려해주는 클래스
public class FileOutputter implements Outputter {

	private String filePath;
	private String fileName;
	
	public FileOutputter() {
		System.out.println("FileOutputter 기본생성자");
	}
	
	public void setFilePath(String filePath) {
		System.out.println("public void setFilePath(String filePath)");
	    this.filePath = filePath;
	}

	public void setFileName(String fileName) {
		System.out.println("public void setFileName(String fileName)");
	    this.fileName = fileName;
	}
	
	@Override
	public void output(String message) {
		
		
	}
}

----------------------------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"
	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.3.xsd">

<!-- sample05 -->
<bean id="fileOutputter" class="sample05.FileOutputter">
	<property name="filePath" value="D:/Spring/"/>
	<property name="fileName" value="result.txt"/>
</bean>

<bean id="messageBeanImpl2" class="sample05.MessageBeanImpl">
	<constructor-arg value="홍길동"/>
	<property name="phone" value="010-1234-5678"/>
	<property name="outputter" ref="fileOutputter"/>
</bean>

</beans>

여기서 순서를 바꾸면

----------------------------applicationContext.xml---------------------------

<!-- sample05 -->

<bean id="messageBeanImpl2" class="sample05.MessageBeanImpl">
	<constructor-arg value="홍길동"/>
	<property name="phone" value="010-1234-5678"/>
	<property name="outputter" ref="fileOutputter"/>
</bean>

<bean id="fileOutputter" class="sample05.FileOutputter">
	<property name="filePath" value="D:/Spring/"/>
	<property name="fileName" value="result.txt"/>
</bean>

</beans>

----------------------------HelloSpring.java---------------------------

MessageBean messageBean = (MessageBean)applicationContext.getBean("messageBeanImpl2");
		messageBean.helloCall();
        
----------------------------FileOutputter.java---------------------------

@Override
	   public void output(String message) {
	      System.out.println("public void output(String message)");
	      
	      //FileWriter fileWriter = new FileWriter(filePath + fileName); //문자열
	      try {//클래스로 생성
	         FileWriter fileWriter = new FileWriter(new File(filePath, fileName));
	         fileWriter.write(message);
	         fileWriter.close();
	      } catch (IOException e) {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      } 
	   }
       
----------------------------applicationContext.xml---------------------------

<bean id="messageBeanImpl2" class="sample05.MessageBeanImpl">
	<constructor-arg value="홍길동"/>
	<property name="phone" value="010-1234-5678"/>
	<property name="outputter" ref="fileOutputter"/>
</bean>

<bean id="fileOutputter" class="sample05.FileOutputter">
	<property name="filePath" value="D:/Spring/"/>
	<property name="fileName" value="result.txt"/>
</bean>

applicationContext.xml에다 경로 지정해줌


스프링과 JDBC

스프링은 JDBC를 비롯하여 ORM프레임워크(myBatis, hibernate, JPA(Java Persistence API))를 지원한다

spring jdbc

commons collections4

commons dbcp

ojdbc11


----------------------------pom.xml---------------------------
<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>
  <groupId>chapter04_XML</groupId>
  <artifactId>chapter04_XML</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
  <!-- Spring Context -->
  <dependencies>
  	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- Connection pool -->
	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-collections4</artifactId>
	    <version>4.4</version>
	</dependency>
	
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-jdbc</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
  	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-dbcp2</artifactId>
	    <version>2.9.0</version>
	</dependency>
	
	<!-- Oracle -->
	<dependency>
	    <groupId>com.oracle.database.jdbc</groupId>
	    <artifactId>ojdbc11</artifactId>
	    <version>23.2.0.0</version>
	</dependency>
	
  <!-- Project Lombok -->
	<dependency>
	    <groupId>org.projectlombok</groupId>
	    <artifactId>lombok</artifactId>
	    <version>1.18.28</version>
	    <scope>provided</scope>
	</dependency>
  </dependencies>

</project>

----------------------------HelloSpring.java---------------------------

package user.main;

import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import user.service.UserService;

public class HelloSpring {
	
	public void menu(ApplicationContext applicationContext) {		
		  Scanner scan = new Scanner(System.in);
		  UserService userService=null;
	      int num;
	      
	      while(true) {
	      System.out.println("***********");
	      System.out.println("  1. 입력");
	      System.out.println("  2. 출력");
	      System.out.println("  3. 수정");
	      System.out.println("  4. 삭제");
	      System.out.println("  5. 끝");
	      System.out.println("***********");
	      System.out.print("번호 입력 : ");
	      num = scan.nextInt();
	      
	      System.out.println();
	      
	      
	         if(num == 5) break;
	         
	         if(num == 1)
	        	 userService = (UserService)applicationContext.getBean("userInsertService");
	         else if(num == 2)
	        	 userService = (UserService)applicationContext.getBean("userSelectService");
	         else if(num == 3)
	        	 userService = (UserService)applicationContext.getBean("userUpdateService");
	         else if(num == 4)
	        	 userService = (UserService)applicationContext.getBean("userDeleteService");
	         
	         userService.execute();
		}//while
		
	}

	public static void main(String[] args) {
		
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/ApplicationContext.xml"); // - 사용하여 연결하고
		HelloSpring helloSpring = applicationContext.getBean("helloSpring", HelloSpring.class); // - 불러오고
		helloSpring.menu(applicationContext);
		System.out.println("프로그램을 종료합니다.");
	}
}

----------------------------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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		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.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- Connection Pool & DataSource -->
	<!--  
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
		<property name="username" value="c##java"/>
		<property name="password" value="1234"/>
	</bean>
	-->
	<!--  
	<bean id="dataSource" 
	    class="org.apache.commons.dbcp2.BasicDataSource"
	    p:driverClassName="oracle.jdbc.driver.OracleDriver"
	    p:url="jdbc:oracle:thin:@localhost:1521:xe"
	    p:username="c##java"
	    p:password="1234"/>
	-->
	<context:property-placeholder location="classpath:spring/db.properties"/>
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	

	<bean id="helloSpring" class="user.main.HelloSpring"/>
	
	<bean id="userInsertService" class="user.service.UserInsertService">
		<property name="userDTO" ref="userDTO"/>
		<property name="userDAO" ref="userDAOImpl"/>
	</bean>
	
	<bean id="userSelectService" class="user.service.UserSelectService"/>
	
	<bean id="userDTO" class="user.bean.UserDTO"></bean>
	
	<bean id="userDAOImpl" class="user.dao.UserDAOImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"/> <!-- 의존관계 - jdbcTemplate과 연결 -->
	</bean>
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg ref="dataSource"/> <!-- connection pool 값을 제공 -->
	</bean>
	
	<bean id="userUpdateService" class="user.service.UserUpdateService"/>
	<bean id="userDeleteService" class="user.service.UserDeleteService"/>
	

</beans>

----------------------------db.properties---------------------------

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=c##java
jdbc.password=1234

----------------------------UserDTO.java---------------------------

package user.bean;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter

public class UserDTO {
	
	private String name;
	private String id;
	private String pwd;

}

----------------------------UserInsertService.java---------------------------

package user.service;

import java.util.Scanner;

import lombok.Setter;
import user.bean.UserDTO;
import user.dao.UserDAO;

public class UserInsertService implements UserService {
	
	@Setter
	private UserDTO userDTO;
	
	@Setter
	private UserDAO userDAO;
	
	@Override
	public void execute() {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("이름 입력 : ");
		String name = scan.next();
		System.out.print("아이디 입력 : ");
		String id = scan.next();
		System.out.print("비밀번호  입력 : ");
		String pwd = scan.next();
		
		System.out.println();
		
		userDTO.setName(name);
		userDTO.setId(id);
		userDTO.setPwd(pwd);
		
		// DB로 가자
		userDAO.write(userDTO);
		
		System.out.println(name + "님의 데이터를 저장하였습니다.");
		

	}

}

----------------------------UserSelectService.java---------------------------

package user.service;

public class UserSelectService implements UserService {

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}

}

----------------------------UserDAO.interface---------------------------

package user.dao;

import user.bean.UserDTO;

public interface UserDAO {

	public void write(UserDTO userDTO);

}

----------------------------UserDAOImpl.java---------------------------

package user.dao;

import org.springframework.jdbc.core.JdbcTemplate;

import lombok.Setter;
import user.bean.UserDTO;

public class UserDAOImpl implements UserDAO {
	
	@Setter
	private JdbcTemplate jdbcTemplate; // 얘가 귀찮은거 다해줌 

	@Override
	public void write(UserDTO userDTO) {
		String sql = "insert into usertable values(?,?,?)";
		jdbcTemplate.update(sql, userDTO.getName(), userDTO.getId(), userDTO.getPwd());
	}
}

commit을 안해줘도 자바에서 주는건 자동 commit

0개의 댓글