반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 자바스크립트 코딩테스트
- 정보처리기사정리
- 평일코딩
- 리액트네이티브
- 국비코딩
- 타입스크립트
- Java의정석
- 정보처리기사실기요약
- 자바의정석
- react
- CSS
- 정보처리기사
- 정보처리기사실기
- spring
- 정보처리기사실기정리
- 코딩테스트
- 이안의평일코딩
- 자바스크립트
- javascript
- 오라클
- 정보처리기사요약
- 스프링
- 국비IT
- 리액트
- ReactNative
- Oracle
- typescript
- VUE
- php
- 자스코테
Archives
- Today
- Total
이안의 평일코딩
Spring 5일차 - Repository 본문
반응형
2020.10.26(월)
src/main/java
app.xml (beans, context, p)
<?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:p="http://www.springframework.org/schema/p"
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">
<!-- 클래스를 패키지 단위로 메모리 할당 -->
<context:component-scan base-package="com.sist.di"/>
</beans>
app2.xml (beans. context, p)
<?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:p="http://www.springframework.org/schema/p"
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">
<!--
1. 사용자 정의 클래스 등록 : 패키지 단위
2. AOP => 반복 코딩 제거 (등록) ==> 7장
=================================
3. DataSource설정
4. DataSource => 트랜잭션 등록
5. SqlSessionFactoryBean 설정
================================= 8장
6. WebSocket
7. 보안 설정
-->
<context:component-scan base-package="com.sist.di2"/>
<!-- 어노테이션을 이용해서 메모리 할당 -->
<!--모든 DAO에 적용되는 데이터설정 -->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="oracle.jdbc.driver.OracleDriver"
p:url="jdbc:oracle:thin:@211.238.142.000:1521:XE"
p:username="hr"
p:password="happy"
/>
<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="ds"
p:configLocation="classpath:Config.xml"
/>
<!--
1. 스프링 = 클래스를 관리
================
생성 => 필요한 데이터 첨부(DI) => 소멸
==================
1) 일반 데이터 (setter,constructor)
2) 클래스 자체를 첨부 (@Autowired:생성된 클래스 객체의 주소)
====
1) XML로 생성
<bean id="" class="">
2) Annotation으로 생성
<context:component-scan base-package="패키지명">
스프링에 의해 생성되는 클래스
= 클래스 위에 Annotation을 사용
@Component,@Repository,@Controller,@RestController,@Service
프로그래머가 직접 생성하는 클래스 (VO,interface)
=> DI
= @Autowired : 스프링에서 자동으로 첨부
= @Resource : 스프링에 저장되어 있는 객체중에 지정해서 가지고 온다
interface I
class A implements I
class B implements I
@Autowired => 오류 ( A , B ) : 단점은 원하는 클래스를 지정할 수 없다
=> I i;
@Resource(name="b")
=> I i
=> 스프링에서 미리 생성되어 있는 클래스 객체 주소를 이용할 때 사용
=> 기능이 있는 모든 클래스는 스프링에 맡긴다
필요시마다 스프링을 통해서 얻어 온다
=> @Autowired , @Resource(name="b")를 사용하기 위해서
반드시 스프링에서 메모리 할당을 해야 사용 할 수 있다
-->
</beans>
app3.xml (beans, context)
<?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">
<context:component-scan base-package="com.sist.di3"/>
</beans>
Config.xml
<?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>
<typeAlias type="com.sist.di2.MusicVO" alias="MusicVO"/>
<typeAlias type="com.sist.di2.MovieVO" alias="MovieVO"/>
</typeAliases>
<mappers>
<mapper resource="com/sist/di2/music-mapper.xml"/>
<mapper resource="com/sist/di2/movie-mapper.xml"/>
</mappers>
</configuration>
src/main/java
com.sist.di
MainClass.java
package com.sist.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
// 클라이언트에서 데이터 볼 수 있게 만드는 클래스
// WEB => JSP(View)
import java.util.*;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext app=
new ClassPathXmlApplicationContext("app.xml");
MusicDAO dao=(MusicDAO)app.getBean("musicDAO");
List<MusicVO> list=dao.musicListData();
for(MusicVO vo:list)
{
System.out.println("번호:"+vo.getMno());
System.out.println("노래명:"+vo.getTitle());
System.out.println("가수명:"+vo.getSinger());
System.out.println("앨범:"+vo.getAlbum());
System.out.println("======================================");
}
}
}
MovieDAO.java
package com.sist.di;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
// 스프링에서 관리
/*
* 스프링에서 관리 대상(여러곳에서 사용하는 기능)
* 1) DAO
* 2) Manager
* ================= web에서 사용
* 3) Model
* 4) Service
*/
import java.util.*;
/*
* BasicDataSource => SqlSessionFactoryBean => MusicDAO
* 오라클 정보 Connection => PreparedStatement,ResultSet
*/
/*
* <bean id="dao" class="com.sist.di.MusicDAO"
p:sqlSessionFactory-ref="ssf"
/>
*/
@Repository
// ID : musicDAO
public class MusicDAO extends SqlSessionDaoSupport{
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
// TODO Auto-generated method stub
super.setSqlSessionFactory(sqlSessionFactory);
}
public List<MusicVO> musicListData()
{
return getSqlSession().selectList("musicListData");
}
}
MovieVO.java
package com.sist.di;
/*
* ~VO
* ~DTO
* ~Bean
* =============> 데이터를 모아서 전송 (일반 데이터형)
* 스프링에서 메모리 할당을 하지 않고 프로그래머가 필요시마다 메모리 할당을 한다
*/
public class MusicVO {
private int mno;
private String title;
private String singer;
private String album;
public int getMno() {
return mno;
}
public void setMno(int mno) {
this.mno = mno;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
}
MyBasicDataSource.java
package com.sist.di;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Component;
/*
* <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="oracle.jdbc.driver.OracleDriver"
p:url="jdbc:oracle:thin:@211.238.142.000:1521:XE"
p:username="hr"
p:password="happy"
/>
*/
// 데이터 베이스 정보
// 메모리 할당
/*
* @Component : 일반 클래스
* @Repository : 저장소 (DataBase와 관련) => DAO
* ================= Web
* @Controller : Model ==> return 사이트 주소(JSP파일명)
* @RestController : Model ==> return 일반 문자열 (ajax,json...)
* =================
* @Service : Manager,DAO가 여러개일때 묶어서 사용 BI
*/
@Component
// ID => myBasicDataSource
public class MyBasicDataSource extends BasicDataSource{
public MyBasicDataSource()
{
setDriverClassName("oracle.jdbc.driver.OracleDriver");
setUrl("jdbc:oracle:thin:@211.238.142.000:1521:XE");
setUsername("hr");
setPassword("happy");
}
}
MySqlSessionFactoryBean.java
package com.sist.di;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
/*
* <bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="ds"
p:configLocation="classpath:Config.xml"
/>
*/
@Component
// ID : mySqlSessionFactoryBean
// 라이브러리 => XML(공통 사용부분)
// 사용자 정의 => Annotation
public class MySqlSessionFactoryBean extends SqlSessionFactoryBean{
// CONSTRUCTOR (생성자), FIELD(멤버변수), METHOD(메소드), PARAMETER(매개변수)
/*
* class A
* {
* @Autowired
* B b;
*
* @Autowired
* public A(B b){}
*
* @Autowired
* public void setB(B b){}
*
* @Autowired
* public void display(B b){}
* }
*/
// p:dataSource-ref="ds"
@Autowired
public void setDataSource(DataSource dataSource) {
// TODO Auto-generated method stub
super.setDataSource(dataSource);
}
public MySqlSessionFactoryBean()
{
try
{
// p:configLocation="classpath:Config.xml"
Resource res=new ClassPathResource("Config.xml");
setConfigLocation(res);
}catch(Exception ex){}
}
}
music-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di.music-mapper">
<!-- PreparedStatement (SQL문장을 전송), ResultSet 설정(결과값) -->
<select id="musicListData" resultType="MusicVO">
SELECT mno,title,singer,album
FROM genie_music
</select>
</mapper>
com.sist.di2
MainClass.java
package com.sist.di2;
// 메모리 할당 => DAO를 자동주입으로 받는다
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class MainClass {
@Autowired
private MusicDAO dao;
@Autowired
private MovieDAO mDao;
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext app=
new ClassPathXmlApplicationContext("app2.xml");
MainClass mc=(MainClass)app.getBean("mainClass");
//MainClass mc=new MainClass();
List<MusicVO> list=mc.dao.musicListData();
for(MusicVO vo:list)
{
System.out.println("번호:"+vo.getMno());
System.out.println("노래명:"+vo.getTitle());
System.out.println("가수명:"+vo.getSinger());
System.out.println("앨범:"+vo.getAlbum());
System.out.println("======================================");
}
System.out.println("===== 영화 목록 ======");
List<MovieVO> mList=mc.mDao.movieListData();
for(MovieVO vo:mList)
{
System.out.println("번호:"+vo.getNo());
System.out.println("영화명:"+vo.getTitle());
System.out.println("출연:"+vo.getActor());
System.out.println("감독:"+vo.getDirector());
}
}
}
MovieDAO.java
package com.sist.di2;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/*
* public void display(@Autowired A a,B b)
*/
import java.util.*;
@Repository
public class MovieDAO extends SqlSessionDaoSupport{
// CONSTRUCTOR, FIELD, METHOD, PARAMETER
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
// TODO Auto-generated method stub
super.setSqlSessionFactory(sqlSessionFactory);
}
// ssf
public List<MovieVO> movieListData()
{
return getSqlSession().selectList("movieListData");
}
}
MovieVO.java
package com.sist.di2;
public class MovieVO {
private int no;
private String title;
private String actor;
private String director;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
}
MusicDAO.java
package com.sist.di2;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
// 스프링에서 관리
/*
* 스프링에서 관리 대상(여러곳에서 사용하는 기능)
* 1) DAO
* 2) Manager
* ================= web에서 사용
* 3) Model
* 4) Service
*/
import java.util.*;
/*
* BasicDataSource => SqlSessionFactoryBean => MusicDAO
* 오라클 정보 Connection => PreparedStatement,ResultSet
*/
/*
* <bean id="dao" class="com.sist.di.MusicDAO"
p:sqlSessionFactory-ref="ssf"
/>
*/
@Repository
// ID : musicDAO
public class MusicDAO extends SqlSessionDaoSupport{
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
// TODO Auto-generated method stub
super.setSqlSessionFactory(sqlSessionFactory);
}
public List<MusicVO> musicListData()
{
return getSqlSession().selectList("musicListData");
}
}
MusicVO.java
package com.sist.di2;
/*
* ~VO
* ~DTO
* ~Bean
* =============> 데이터를 모아서 전송 (일반 데이터형)
* 스프링에서 메모리 할당을 하지 않고 프로그래머가 필요시마다 메모리 할당을 한다
*/
public class MusicVO {
private int mno;
private String title;
private String singer;
private String album;
public int getMno() {
return mno;
}
public void setMno(int mno) {
this.mno = mno;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
}
movie-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di2.movie-mapper">
<select id="movieListData" resultType="MovieVO">
SELECT no,title,actor,director
FROM daum_movie
WHERE cateno=1
</select>
</mapper>
music-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di.music-mapper">
<!-- PreparedStatement (SQL문장을 전송), ResultSet 설정(결과값) -->
<select id="musicListData" resultType="MusicVO">
SELECT mno,title,singer,album
FROM genie_music
</select>
</mapper>
com.sist.di3
MainClass.java
package com.sist.di3;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/*
* TYPE : 클래스 위에
* METHOD : 메소드 위에
* FIELD : 멤버 변수
* CONSTRUCTOR : 생성자 위에
* PARAMETER : 매개변수 옆에
*/
@Component("mc")
public class MainClass {
// FIELD, METHOD, TYPE
@Resource(name="sa")
private Sawon sa;
@Resource(name="mem")
private Member mem;
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext app=new ClassPathXmlApplicationContext("app3.xml");
MainClass mc=(MainClass)app.getBean("mc");
//MainClass mc=new MainClass();
mc.sa.print();
mc.mem.print();
}
}
Member.java
package com.sist.di3;
import org.springframework.stereotype.Component;
/*
* 1. 멤버변수 초기화
* 1) 명시적 초기화
* =============
* 2) setter
* 3) 생성자
*/
@Component("mem")
public class Member {
private String name="홍길동";
private String addr="서울";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public void print()
{
System.out.println("이름:"+name);
System.out.println("주소:"+addr);
}
}
Sawon.java
package com.sist.di3;
import org.springframework.stereotype.Component;
@Component("sa")
public class Sawon {
private String name="½ÉûÀÌ";
private String dept="°³¹ßºÎ";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public void print()
{
System.out.println("À̸§:"+name);
System.out.println("ºÎ¼:"+dept);
}
}
반응형
'Back-end > Spring' 카테고리의 다른 글
Spring 7일차 - XML MVC구조 (0) | 2020.11.02 |
---|---|
Spring 6일차 - ComponentScan (0) | 2020.10.31 |
Spring 4일차 - Autowired (0) | 2020.10.23 |
Spring 3일차 - Container (0) | 2020.10.22 |
Spring 2일차 - XML, Configuration (0) | 2020.10.21 |
Comments