'스프링3.0' 카테고리의 다른 글
MyBatis (0) | 2012.07.03 |
---|---|
스프링 3.0 + ibatise (0) | 2012.07.03 |
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
web.xml 구현부 encoder (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
MyBatis (0) | 2012.07.03 |
---|---|
스프링 3.0 + ibatise (0) | 2012.07.03 |
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
web.xml 구현부 encoder (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
Version 3를 사용하세요~
가끔 특정 테이블의 컬럼의 목록을 구할 필요가 있을 때가 있다. DBMS에서 테이블의 정보를 구해오는 것은 각각의 DB마다 상이하다. (예. 오라클의 경우는 딕셔너리 테이블에서 가져올 수 있다) JDBC의 메타데이터를 이용하면 쉽게 가져올 수 있다.
참고 : Get column names of a table using ResultSetMetaData
그럼 MyBatis를 사용해서 DB Mapper를 사용하는 경우 별도의 JDBC 연결 설정을 만들어서 이용해야 하나?
그러면 DB 접속 환경이 한군데가 변하게 되면 MyBatis 및 JDBC 모두 변경을 해야 한다. 이것은 중복이다. DRY원칙 위반이다. 설정값을 하나로 이용하는 방법도 있지만 이것 역시 귀찮다.
쉬운방법으로는 SqlSessionFactory에서 openSession() 메소드를 통해 세션을 연 다음 SqlSession 인터페이스에서
getConnection() 메소드를 이용하여 java.sql.Connection을 가져오면 JDBC의 기능을 온전히 이용할 수 있다.
말로만 설명하면 어려우니 예제를 보여주겠습니다.
} finally {
session.close();
}
위에서 보면 columns라는 ArrayList타입의 리스트에 컬럼명을 넣습니다.
executeQuery에서 'WHERE 0=1'로 거짓조건을 주는 이유는 데이터를 가져오지 않게 하기 위함입니다.
columns를 이용해서 컬럼 목록을 이용하면 됩니다.
SQL 매핑 프레임워크 iBATIS가 이름이 MyBatis로 바뀌었다.
클린턴 비긴이 처음 개발했던 아이바티스는 아파치 프로젝트로 들어갔다가 2010년 6월 16일 은퇴(retire)하고 구글 코드쪽에서mybatis라는 이름으로 이동했다. 지금 시점(2010 12월)에서는 MyBatis 3.0.3 버전이 릴리즈 되어 있다.
“카드 정보 1억 3,000만 건 도난”, 주범은 SQL 인젝션
이클립스에서 느낌표가 나오면 왠지 모르게 짜증이 난다
[기존]
[수정]
주소가 수정되었나보다. 브라우저에서 주소창에 치면 이전 것도 다운로드 되는데 이클립스에서는 왜 안되지?
다른 sql-map, dao도 올려놓자
아놔~ 그 문제인줄 알았는데,
회사에서는 외부 인터넷에 연결하기 위해서 프록시 서버를 연결해야 하는데 이클립스에 세팅을 해줘야 하기 때문이었다.
네트워크 연결이 안되니 dtd 파일을 다운받을 수 없고 xml validation도 할 수 없는 것이 었다.
위 책의 필요한 사전 배경지식: Java, JDBC(매핑+), SQL, XML
외부 링크 : 아이바티스 커뮤니티(http://ibatis.apache.org)
SVN : Subversion Source Control
JIRA: for 이슈 트래킹(아틀라시안)
Confluence : wiki 문서 작성
소스 코드 : 매닝 출판사 웹 사이트(www.manning.com/begin)
위키북스 오픈소스 & 웹 시리즈 에디터 일래스틱 온라인(http://web2.0business.or.kr/)
머리말
퍼시스턴스 계층에 적용할 프레임워크
iBATIS : 더 빠른 JDBC 코딩을 위한 일반화된 프레임워크
특징
성능 - 구조적 강점(데이터 접근 속도 높여주는 JOIN매핑)
관심사의 분리 - 설계를 향상(차후 유지보수성 위해)
작업의 분배 - 팀을 세분화하는 것을 도움
이식성 - 어떤 프로그래밍언어로도 구현 가능
언제 사용하지 말아야 하나?
개발자가 모든 것에 대해 영원한 결정권 소유
완전히 동적인 SQL을 요구시
비 관계형 데이터베이스 사용
(주로)관계형 데이터베이스를 위해 설계
배포판 얻기
바이너리 배포판: 가장 빠르고 쉬운 방법
소스로부터 빌드하기
배포판의 구조
/doc
/lib
/src
애플리케이션에 iBATIS 붙이기
클래스패스 추가(iBATIS 파일 경로 컴파일시, 실행시)
단독 실행 애플리케이션
클래스패스 옵션 추가
웹 애플리케이션
JRE 공유 디렉토리(lib/ext 디렉토리)에 올려서 사용가능하지만 가급적 피할 것
SQL Maps 설정 파일
<SqlMapConfig.xml>
<properties> 요소 - 외부에서 이름/값 쌍의 리스트를 제공
속성
resource - 클래스 패스상에 있는 리소스(or 파일)
소스(db.properties)
<setting> 요소
<typeAlias> 요소 - FQCN(완전한 형태의 클래스 이름, Fully Qualified Class Name) 대신 별칭을 붙임
예)
기본 내장 별칭들
트랜잭션 매니저의 별칭
데이터 타입
데이터 소스 팩토리 타입
캐시 컨트롤러 타입
XML 결과 타입
<transactionManager> 요소
type - 어떤 트랜잭션 관리자르 사용할지 결정
type 속성 - 어떤 클래스의 객체를 생성해서 데이터 소스 팩토리를 얻어올지를 정하는 속성
<typeHandler>
<sqlMap> 요소
SQL Map API
SqlMapClient 인터페이스
queryForObject() - 데이터베이스로부터 한 개의 레코드를 가져다가 자바 객체에 저장
Object queryForObject(String id, Object parameter) throws SQLException;
Object queryForObject(String id, Object parameter, Object result) throws SQLException;
queryForList() - 한 개 이상의 레코드를 가져와서 자바 객체의 List를 만드는 데 사용
List queryForList(String id, Object parameter) throws SQLException;
List queryForList(String id, Object parameter, int skip, int max) throws SQLException;
queryForMap() - 데이터베이스로부터 한 개 혹은 그 이상의 레코드를 가져올 때 자바 객체의 Map을 반환
Map queryForMap(String id, Object parameter, String key) throws SQLException;
key : 결과 객체를 가리키는 키, -> 지정된 프로퍼티의 값
Map queryForMap(String id, Object parameter, String key, String value) throws SQLException;
결과값 객체 -> value 파라미터에 지정된 프로퍼티 값이 됨
non-query 구문
데이터 갱신
insert 메소드
Object inser(String id, Object parameterObject) throws SQLException;
update 메소드
int update(String id, Object parameterObject) throws SQLException;
delete 메소드
int delete(String id, Object parameterObject) throws SQLException;
매핑 구문
<insert> | id, parameterClass, parameterMap
<sql> | id
<include> | refid
iBATIS에서 XML 사용
XML 파라미터
XML로 결과 생성
비지니스 객체 모델(도메인 클래스) : 처리할 도메인을 객체 지향적으로 묘사
프리젠테이션 계층 : 출력(애플리케이션의 데이터/제어화면)하는 역할
웹 애플리케이션
단점: 높은 수준의 사용자 제어 방식, 복잡한 데이터 처리 어려움
리치 클라이언트 방식
복합적 리치 클라이언트(웹 애플리케이션 + 리치 클라이언트 방식)
단점: 애플리케이션의 개발과 배치에 더 많은 소프트웨어 필요
비지니스 로직 계층(서비스 클래스) - 애플리케이션이 제공하는 포괄적인 서비스들을 표현
퍼시스턴스 계층 - 객체에 저장된 데이터(저장소, 객체 가져오기)
내부 계층
추상 계층 : 퍼스스턴스 계층에 일관성 있고 의미 있는 인터페이스 제공
퍼시스턴스 프레임워크 : 드라이버(or 인터페이스)와 소통하는 책임
표준API - 반복적이고 부차적인 코드가 필요
드라이버 / 인터페이스
관계형 데이터베이스의 사용 이유? - 무결성, 성능, 보안
무결성 - 데이터의 일관성, 신뢰, 값의 정확성 보장
성능 - 설계, 소프트웨어 튜닝, 하드웨어
데이터베이스 형태(4가지)
애플리케이션 데이터베이스 - 작고 단순한 형태, 외부 영향 적음
기업용 데이터베이스 - 큰 규모, 외부의 영향 큼
레거시 데이터베이스 - 오래된 데이터베이스(보잡성, 뒤죽박죽 설계, 의존성. age)
iBATIS - 데이터 매퍼
매퍼계층: 객체와 데이터베이스 그리고 매퍼 자체를 독립적으로 유지 + 객체와 데이터베이스 간에 데이터를 이동
매핑방법
SQL 구문 - 입력과 출력으로 구분
예) 입력 first_name, last_name / 출력 1234
XML 서술 파일 : SQL 구문의 입력과 출력을 매핑
위 코드를 수행하는 자바 코드
위 코드를 수행하는 C# 코드
JDBC, ADO.NET 코드 작성 대신
예) JDBC vs iBATIS
JDBC
iBATIS
실행 코드
자바빈즈를 PreparedStatement 파라미터와 ResultSet으로 맵핑시켜주는 기능을 담당
디미터 법칙(Law of Demeter) "각 계층은 다른 계층에 대해 오직 제한된 정보만을 가질 수 있다: 오직 현재 계층에 인접한 계층에 대해서만."
왜 iBATIS대신에 Spring을 사용할까?
iBATIS DAO 계층
DAO 패턴을 사용: 결함도가 낮아짐(decoupling) -> 테스트하기 쉽다
효율적인 DAO 계층
구현체에서 인터페이스 분리
이유
IDE : 분리 과정 쉽게 처리 가능
인터페이스를 만들 때 구현 클래스를 어떤 다른 데잍터베이스를 다루는 툴에 종속적인 부분에 노출 가능성 높음
노출: DAO가 아닌 데이터 접근 구현체에 애플리케이션을 묶어버림
예) 'Fast Lane Reader'패턴을 사용하는 웹 애플리케이션 - JDBC 코드가 뷰 계층과 직접 소통 (테스트 어려워짐)
SQL Maps API를 직접 사용하는 애플리케이션 -> 캡슐화된 API
예) sqlMapClient 객체의 queryForList() 메소드를 호출하는 클래스 - > 작성한 DAO 클래스를 호출하게 리팩토링, 클래스의 메소드에서는 List 객체를 반환
외부에서 설정된 팩토리(factory)를 사용하여 구현체의 결합도 낮추기
인터페이스와 구현체 둘 다 DAO를 사용하는 클래스에 노출(인터페이스에 대한 의존성을 DAO를 사용하는 클래스에 추가한 셈)시키면 안됨
[구현체]-[DAO]-[interface]-> 구현체를 어떻게 사용할 수 있을 것인가?
DAO factory
public인테피이스는 getInstance()와 getDao() 두개의 메소드로 이루어져 있음
"dao.factory.config",
defaultConfigLocation
);
스프링: 데이터 매퍼의 두 가지 버전(1.3, 2.0)을 지원
버전 2.0 : SqlMapClientXxx (SqlMapClientTemplate 클래스 사용: 내부적으로 iBATIS의 SqlMapClient 사용)
SqlMapClient를 스프링 빈으로 설정 : SqlMapClientFactoryBean 클래스 이용
<bean id="sqlMapClinet" class="org.springframework.orm.ibatis.SqlMapClinetFactoryBean"
sqlMapConfig.xml
GuestBook.xml
<typeAlias alias="Message" type="kame.spring.questbook.service.Message" />
<parameterMap id="messageParamMap" class="Message">
자동으로 클래스패스를 잡아주니 라이브러리에 추가만 해주면 된다.
1. Library Name에 알기 쉬운 이름을 붙여준다(iBATIS2.3.0.677)
iBATIS를 통해 더 즐겁게 개발하고, 또 개발의 재미도 느끼고 야근도 덜 할 수 있기를 기원한다. - xx
불가지론자(경험해보지 않은 것은 믿을 수 없다) - xxi
"망치를 가진 사람은 모든 것을 못으로 본다" , 환경이 다양하면 다양한 도구가 필요한 법 - xxii
책을 쓰는 것은 (소프트웨어를 작성)하는 것보다 더 어렵다. - xxiv
돈을 위해 낮에는 일을 하고 명성과 영광을 얻기 위해 밤에는 오픈소스 소프트웨어(또는 책)를 작성하기 위해 시간을 보낸다.(클린턴 비긴) - xxiv
긱(geek: 학업이나 일, 컴퓨터 등에 몰두하다 보니 세상물정과는 거리가 멀어진 사람 / 특정 분야에 대해 광적인 사람), 우리는 첫 번째 컴퓨터를 가졌을때의 좋은 기억이 있고 그 컴퓨터를 사주는 투자가 나중에 좋은 결과를 낳게 된다는 것을 아는 부모님을 신뢰한다. - xxv
책은 무언가를 배우는 최고의 방법, 종이책이 전자책으로 대체되거나 뒤통수에 잭을 꼽아서 몇 초안에 정보를 업로드하는 방식으로 바뀔 거라는 등 많은 억측, 나는 책을 좋아한다. 책은 편리하게 갖고 다닐 수 있고, 다루기도 쉽기 때문이다. 책에 메모를 남기고, 종이를 접고, 반으로 쪼개서 갖고 다닐 수도 있다.(클린턴 비긴) - xxvii
사람들은 스스로 동기를 부여받아 탐구하는 동안 배운 것들을 기억(인지 과학), 인류는 행동하며(in action) 배운다. - xxxii
db.properties 위치
contextConfigLocation (0) | 2012.07.04 |
---|---|
스프링 3.0 + ibatise (0) | 2012.07.03 |
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
web.xml 구현부 encoder (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
FOCUS :
Eclipse + Maven + Spring Framework 개발환경 설정.
Reference :
1. http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. http://www.eclipse.org/downloads
3. http://openness.tistory.com/107
4. http://tomcat.apache.org/download-70.cgi
5. http://blog.daum.net/istae0430/279
6. http://archive.apache.org/dist/tomcat/tomcat-connectors/native/
7. http://blog.doortts.com/59
8. http://alexk.springnote.com/pages/3501753#toc_2
9. http://maven.apache.org/download.html
10. http://eclipse.org/m2e/
11. http://eclipse.org/m2e/download
12. http://stackoverflow.com/questions/2921473/m2eclipse-eclipse-is-running-in-a-jre-but-a-jdk-is-required
13. pom reference ( http://maven.apache.org/pom.html)
14. http://kongkk.springnote.com/pages/8115902
15. http://sepiroth11.tistory.com/entry/SetPropertiesRuleServerServiceEngineHostContext-Setting-property-source-to-orgeclipsejstjeeserver%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EB%AA%85-did-not-find-a-matching-property
16. http://entireboy.egloos.com/4534698
Need to known :
The APR based Apache Tomcat Native library
Maven http://maven.apache.org/
1) How do i build my project http://www.avajava.com/tutorials/lessons/how-do-i-build-my-project.html
2) build lifecycle phase :http://cvs.peopleware.be/training/maven/maven2/buildLifecyclePhases.html#site
Spring Framework http://www.springsource.org/ ,
1) Spring Framework module 설명 : http://blog.naver.com/gigar/60121489281
spring Framework 개발환경 설정에 대해 정리해 본다.
개발 환경 설정 하는데, 왜 이리 걸리는게 많은지, 환경 설정 하다가 포기하겠당 ㅋㅋ
그래서 다시 한번 정리!!
- 개발환경은 아래와 같은 순서로 설정 (for windows 7)
1. java 설치
2. eclipse 설치.
3. tomcat 설치 + eclipse wts 설정
4. maven 설치 + eclipse m2eclipse 설치
5. spring Framework 설정
1. java 설치
아래의 URL 에서 JDK 7 download
http://www.oracle.com/technetwork/java/javase/downloads/index.html
JDK7 설치 후, 윈도우 환경변수에 JAVA_HOME 설정
JAVA_HOME --> C:\Dev\Java\jdk1.7.0
2. Eclipse(Indigo SR1) 설치
아래의 URL 에서 Eclipse IDE for Java EE Developers download
http://www.eclipse.org/downloads/
받은파일 (eclipse-jee-indigo-SR1-win32.zip)의 압축해제로 eclipse 설치
3. tomcat 설치 + eclipse wts 설정 ( 참고 : http://openness.tistory.com/107)
아래의 URL에서 tomcat 7.0 download
http://tomcat.apache.org/download-70.cgi
받은파일 압축해제로 tomcat 설치
tomcat 설치 후, 윈도우 환경변수에 CATALINA_HOME 설정
CATALINA_HOME -->D:\tomcat
Eclipse 에서 New > Other > Server > Apache Tomcat v7.0 Server 선택
tomcat installation directory -> d:\tomcat 설정
jre -> jre7 (C:\Dev\Java\jdk1.7.0) 설정
위와 같이 설정하면
하단의 Servers tab 에 Tomcat v7.0 Server at localhost [Stopped, Republish] 라고 나온다.
Tomcat v7.0 Server at localhost Start 후, 웹브라우저에 http://localhost:8080 로 실행 했을때 아래와 같이 나오면 정상
<dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.4.0</version> </dependency><dependencies> <repositories> <repository> <id>mesir-repo</id> <url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url> </repository> </repositories> |
mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.0 -Dpackaging=jar -DgeneratePom=true |
<dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.0</version> </dependency><dependencies> |
브라우저 실행후 http://localhost:8080/springTest2/test1.do 실행 시켰더니 원하는 페이지가 떴다.
휴우~
중간 중간의 고비를 잘 넘기고 spring framework으로 만들어진 간단한 페이지가 떴다.
spring Framework 개발환경 설정(1) 에서는 eclips Maven project 로 spring Framework 설정방법을 살펴봤다.
이번에는 이미 설정되어 있는 spring Framework에 iBatis 설정을 추가한다.
FOCUS
spring Framework 에 iBatis 설정 하고 테스트 페이지 만들기
Reference
1. jsp taglib 사용 위해 maven 에 설정 해야 할 dependency?
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
2. iBatis 설정하여 개발할때 편하게 개발 할 수 있는 순서
1)Table 스키마 확인
2) iBatis resultMap 작성
3) DB Query 문 작성
4) DAO 작성
5) JSP 작성
6) Service & Controller 작성
7) 필요하면 환경설정파일 변경.
Need to know
iBatis 사용법.
iBatis 연동을 위해 아래의 작업을 진행한다.
1. pom.xml에 iBatis dependency 추가.
2. /WEB-INF/web.xml 수정.
3. /WEB-INF/spring/spring-config.xml 생성 .
4. /WEB-INF/sql-map-config.xml 생성
5. Test.xml(sqlmap 파일) 생성.
6. dao 파일 생성
7. domain 생성
8. Controller 수정
9. JSP 수정
1. pom.xml 에 iBatis dependency 추가.
( spring Framework 개발환경 설정(1) 에 첨부된 파일 이미 추가되어 있슴)
<dependencies>
...
<!-- DB- jdbc driver 시작 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!-- DB - jdbc driver끝 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.4.726</version>
</dependency>
...
</dependencies>
2. WEB-INF/web.xml 수정
아래의 내용을 web.xml 에 추가.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*-config.xml</param-value>
</context-param>
<listener>
<display-name>SpringContextLoader</display-name>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3. /WEB-INF/spring/spring-config.xml 생성
web.xml 에 선언 후,
/WEB-INF/spring 디렉토리에 *-config.xml 로 명명되는 파일은 spring configuration 용으로 사용.
아래는 spring-config.xml (jdbc , ibatis, dao 설정)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://domain or ip/dbname"/>
<property name="username" value="id"/>
<property name="password" value="password"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="10"/>
<property name="maxWait" value="1000"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<!-- SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="WEB-INF/sql-map-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DAO -->
<bean id="testDao" class="com.springTest2.dao.TestDao">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
</beans>
4. /WEB-INF/sql-map-config.xml 생성
아래의 내용은 query 문이 기록된 xml resource 설정
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<sqlMap resource="com/springTest2/dao/map/Test.xml" />
</sqlMapConfig>
5. Test.xml(sqlmap 파일) 생성.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Test">
<typeAlias alias="TestTableInfo" type="com.springTest2.domain.TestTableInfo" />
<resultMap id="testTableInfoResult" class="TestTableInfo">
<result property="name" column="NAME" />
<result property="age" column="AGE" />
<result property="sex" column="SEX" />
</resultMap>
<!-- testTable 모든 데이터 조회 -->
<select id="getTestTableList" parameterClass="map" resultMap="testTableInfoResult">
SELECT name, age, sex
FROM testTable
</select>
</sqlMap>
6. dao 파일 생성
package com.springTest2.dao;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
public class TestDao extends SqlMapClientDaoSupport{
//testTable list를 조회한다.
public List getTestTableData(Map map ) throws DataAccessException {
return getSqlMapClientTemplate().queryForList("getTestTableList", map);
}
}
7. domain 생성
package com.springTest2.domain;
public class TestTableInfo {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
8. Controller 수정
보통 Controller 에서는 Service Object만 사용하나 지금 테스트 하는 예제는 단순하기때문에 Service단을 생략하고
Controller에서 Dao를 설정하여 사용하였다.
package com.springTest2.controller;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springTest2.dao.TestDao;
@Controller
public class TestController {
@Autowired
private TestDao testDao;
@RequestMapping("/test1.do")
public ModelAndView helloworld(){
String message = "Hello Spring Framework";
ModelAndView mnv = new ModelAndView();
mnv.setViewName("resultPage");
mnv.addObject("message", message);
//query 문에 넘길 param 없으므로 아무값도 설정하지 않는다.
HashMap map = new HashMap();
//testTable data를 조회한다.
List list = testDao.getTestTableData(map);
mnv.addObject("TestTalbeDataList", list);
return mnv;
}
}
9. JSP 수정
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
</head>
<body>
${message}
<br/>
<br/>
<table border="1">
<!- DB에서 조회한 데이터 Display 하는 영역 -->
<c:forEach var="TestTableData" items="${TestTalbeDataList}" >
<tr>
<td>name</td>
<td>age</td>
<td>sex</td>
</tr>
<tr>
<td>${TestTableData.name}</td>
<td>${TestTableData.age}</td>
<td>${TestTableData.sex}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
결과확인
contextConfigLocation (0) | 2012.07.04 |
---|---|
MyBatis (0) | 2012.07.03 |
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
web.xml 구현부 encoder (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
=================================
=================================
먼저 web.xml 에 context-param 울 추가 하자.
여기서 classpath 의 값이 application*.xml 인 이유는
추후 DB 연결인 datasource 구현및 AOP 구현을 위해 만드는 것이다.
applicationAOP.xml 이면 AOP 구현
applicationcontext.xml context 구현
applicationDataSource.xml 이면 DS 구현 이다.
본래 마이바 티스 에서는
MyBatiseFacotry.java
config.xml
을 이런식으로 구현 하게 된다.
dipather의 즉 조립기에서는 연결된 sqlSessionFactoryBean을 만들기 위해서 application 구현부에 등록을 먼저 해야 한다.
applicationDataSource.xml 를 경로에 맞기 생성하자. Datasource 에서는 크게 3개의 컨테이너(bean) 울 구현 해야 한다.
먼저 datasource 를 보자 .
여기서 defaultAutoComiit의 경우 기본 값을 true 이나. comiit(커멧이 무엇인지는 알거라 믿음)이 여기서 ture 인경우 성능에 문제가 발생 된다고 한다.
아마도 select 문 의 경우 commit 필요 업는데도 불필요 하게 실행 되는등등의 문제가 있는듯 하다.
라고 만들면 된다 .
p:configLocation 의 경우
이렇게 구현되어 진다. 기존의 config.xml 이 데이터 베이스에 대한 것에 대하여 다 입력 되어 있었던것을 기억해 두자.
이후에 같은 경로에 applicationcontext.xml 을 만들어 보자. 먼저 할것은
을 추가 하자 db 연결에 대한 설정 파일을 properties 에서 설정 함을 알수 있다.
이렇게 설정만들어 보자. !!
MyBatis 에서 제공하는 MapperFacetoryBean 을 이용하여 프락시(대행)객체를 생성하여 호출
단, 기존 dao의 로직이 있는 경우는 안됨, 해당 로직은 다른곳(서비스)에서 처리 한마디로 마이바티스 를 안만들고 자체적으로 처리됨.
을 추가하자.
그 후에 bean 컨테이너를 짜야 한다.
이런식으로!!!
추가:
p:sqlSessionFactory-ref="sqlSessionFactoryBean" 의 경우 반드시 service 구현부 에서 set 로 구현 되어야 한다.
ex)
이렇게 구현 하자 .
그리고
이것도 까먹지 말자. 생성 할때 추가 하던가 하는게 좋다.
MyBatis (0) | 2012.07.03 |
---|---|
스프링 3.0 + ibatise (0) | 2012.07.03 |
web.xml 구현부 encoder (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
dispathcer 구현부 web-servlet.xml (0) | 2012.05.19 |
spring 구현시에 반드시 추가 해야만 한다. 안그러면 한글이 깨진다.
web,xml 구현
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
을 추가 하자.
스프링 3.0 + ibatise (0) | 2012.07.03 |
---|---|
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
Spring 개발 환경 . (0) | 2012.05.19 |
dispathcer 구현부 web-servlet.xml (0) | 2012.05.19 |
DispatcherServlet web.xml 구현부 (0) | 2012.05.19 |
이클립스에서 스프링을 구현해 보자.
http://www.springsource.org/spring-community-download
접속 하자.
아래와 같이 가입 하라고 나오나. 밑에 단에
(I'd rather not fill in the form. Just take me to the download page)
라고 써있다. 난 그런거 필요 없으니 다운로드
페이지를 보여줘.. 라고 한다 클릭해 주자
라고 나온다 여기서 spring-framework-3.1.1.RELEASE-with-docs.zip 또는 아래 것을 다운 받으면 된다. 되도록이면 doc 가 포함 된 것을 받자.
압축을 푼후에 src 폴더의 내용을 builderpacher 또는 lib 폴더에 추가 시킨다.
대략적으로 사용 하는 것만 따로 추출 해보자면
org.springframework.aop-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.context.support-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.jdbc-3.1.1.RELEASE.jar
org.springframework.orm-3.1.1.RELEASE.jar
org.springframework.transaction-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar
이다. 각자 다운 받아도 되나 통합 사이트 에서 되도록 받자... ; 용량 문제로 한꺼번에 못올린다.
Srping 3.0 sqlSession+DataSource 구현 하기. (Spring+mybatise0 (0) | 2012.05.19 |
---|---|
web.xml 구현부 encoder (0) | 2012.05.19 |
dispathcer 구현부 web-servlet.xml (0) | 2012.05.19 |
DispatcherServlet web.xml 구현부 (0) | 2012.05.19 |
Encoding Filter (web.xml 구현 ) (0) | 2012.05.19 |
-------------------
-------------------
만약 스프링 폴더가 없다면 any-frame 에서 스프링 프레임웍을 이클립스에 넣어야 한다. 이클립스 종료후 이클립스 폴더에
설치 ::http://sararing.tistory.com/entry/Spring-%EA%B0%9C%EB%B0%9C-%ED%99%98%EA%B2%BD
core 한글 (애니프레임) 가이드 PDF:http://dev.anyframejava.org/docs/anyframe/plugin/essential/core/1.0.3/reference/pdf/core-1.0.3.pdf
Spring Bean Configuration File 입력후 경로및 파일이름(web-servlet.xml) 을 넣은 next를 하면
이렇게 나온다 여기서 XSD를 추가 해야만 한다. 지속 적으로 사용 하는 경우에 내용을 복사 해서 사용 해도 된다.
AOP 입력 맨 밑에 3.0.XSD 최신판을 추가 체크 하도록 하자.
추가 할것은
이렇게 된다. 만들어 보자.
만들어진 xml파일의 기본 내용은
이렇게 될것이다.
기본적으로 Spring 에서 MVC 패턴을 구현 하다고 했을때 dipathcer 를 말하는 것은 방금 만든 web-xml 을 말하는 것이다.
dipathcer 구현은 MVC 패턴에서 가장 중심이 되는 것으로 신경써서 구현 해야 한다. 현재 Spring으로 구현 부는 member 와 board 가 있으며 pds 라는 다운로드 까지 포함 되어 있다.
controller 는 anotation을 통해 매핑 되어 있다.
controller 구현 bean을 보자.
위의 내용에 추가 된것을 하나씩 보자.
내용을 보자면 "kr.or.ddit.web.controller" 경로 의 java 파일을 기본 위치로 설정 되어 컨트롤러를 확인 할수 있도록 되어 있다. 기본적으로 jsp 에서 요청시에 맨처음에 dispahcer 에서 실행 하는 것은 매칭된 controller를 찾는 것이다. 이 경로를 찾기 위에서는 HandlerMapping 이 작동 되는데 여기서는 ID="dahmhandlerMapping"
이라는 이름으로 구현 되어 있다. 참고로 fullpath를 이용 하려면 핸드러 매핑,핸드러 어뎁터 두 곳 모두 p:alwaysUseFullPath="true" 를 줘야 한다.
컨트롤러 매핑의 경우 직접적으로 줄수도 있는데
이렇게 하면 된다.
매핑되어 찾아진 controller 에서는 그 결과 값으로 Model 또는 view 값으로 결과 값을 리턴 하며 반환 값으로 String (controller 구현부에서 확인 가능) 으로 보여줄 view를 검색 하게 되는데 그렇게 보여 지는것을 viewResolver 라고 한다.
여기서 확인 해야 할것은. controller 에서 주는 값을 확인 해야 하는데 그 값에 prefix 는 앞에 suffix 는 뒤에 추가 하는 것을 위미 한다. order의 경우 우선순위를 말한다.
dispatcher 에서 업로드 를 구현 할수 있는데 이경우 반드시 아이디 값을 = "multipartResolver" 로 줘야 한다.
insert 문이나 edit 문의 경우 결과 값 == 성공 또는 실패 에 대하여 view 단을 따로 구현 하는것은 매우 비효율 적이라고 할수 있다. 따라서 결과 값에 대하여 하나의 message 형태 도는 클래스 형태로 구분 되어 지는데 message 형태로 출력 dispather 또한 가능 하다.
이렇게 하여
실제 경로의 팔일은
이런식으로 구현하면 된다. message 는 대충 보자.
web.xml 구현부 encoder (0) | 2012.05.19 |
---|---|
Spring 개발 환경 . (0) | 2012.05.19 |
DispatcherServlet web.xml 구현부 (0) | 2012.05.19 |
Encoding Filter (web.xml 구현 ) (0) | 2012.05.19 |
Missing artifact ojdbc:ojdbc:jar:14:compile (0) | 2012.05.18 |
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--//WEB-INF/web-wervlet.xml을 기본설정 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:kr/or/ddit/config/web-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Spring 개발 환경 . (0) | 2012.05.19 |
---|---|
dispathcer 구현부 web-servlet.xml (0) | 2012.05.19 |
Encoding Filter (web.xml 구현 ) (0) | 2012.05.19 |
Missing artifact ojdbc:ojdbc:jar:14:compile (0) | 2012.05.18 |
스프링 3.0 AOP 에러. 문제 해결 (1) | 2012.05.15 |
web.xml 구현
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
dispathcer 구현부 web-servlet.xml (0) | 2012.05.19 |
---|---|
DispatcherServlet web.xml 구현부 (0) | 2012.05.19 |
Missing artifact ojdbc:ojdbc:jar:14:compile (0) | 2012.05.18 |
스프링 3.0 AOP 에러. 문제 해결 (1) | 2012.05.15 |
Spring3.0 Tiles (1) | 2012.05.14 |
전자 정부 프레임웍 .. 프로젝트 만들자 마자 에러 생김..
pom.xml 을 열어 <repository>
<dependency> 추가. 저작권 때문이 라고함. 아놔.
<repository>
<id>mesir-repo</id>
<url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url>
</repository>
And you can get the ojdbc14 jar w/this dep. def.
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
http://www.jroller.com/mert/entry/oracle_s_ojdbc14_jar_mesir 출처
DispatcherServlet web.xml 구현부 (0) | 2012.05.19 |
---|---|
Encoding Filter (web.xml 구현 ) (0) | 2012.05.19 |
스프링 3.0 AOP 에러. 문제 해결 (1) | 2012.05.15 |
Spring3.0 Tiles (1) | 2012.05.14 |
Spring3.0 DB (0) | 2012.05.14 |
에러 메세지 :
심각: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 17 in XML document from file [D:\workJSP\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\dditSpring\WEB-INF\classes\kr\or\ddit\config\applicationAOP.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:advice'.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:advice'.
BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
등의 에러 메세지가 나왔다. 대충 요약 하면 txManager 인 트렌젝션 매니저를 찾지 못한다는 것이다. 코드를 아무리 분석 해도 문제가 해결 안되었으나 문제는 bean 에 있는 것이 아니라. xsi:schemaLocation 에 있었다.
이 스키마 로케이션에
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
으로 추가및 수정 하여 문제 해결!!
but no declaration can be found for element
Encoding Filter (web.xml 구현 ) (0) | 2012.05.19 |
---|---|
Missing artifact ojdbc:ojdbc:jar:14:compile (0) | 2012.05.18 |
Spring3.0 Tiles (1) | 2012.05.14 |
Spring3.0 DB (0) | 2012.05.14 |
Spring3.0 View error filedown (0) | 2012.05.14 |
기본 세팅 Tiles 프로젝트 파일
Missing artifact ojdbc:ojdbc:jar:14:compile (0) | 2012.05.18 |
---|---|
스프링 3.0 AOP 에러. 문제 해결 (1) | 2012.05.15 |
Spring3.0 DB (0) | 2012.05.14 |
Spring3.0 View error filedown (0) | 2012.05.14 |
Spring3.0 MVC 웹요청 처리 (0) | 2012.05.14 |
DB MEMBER1 테이블
멤버등록
스프링 3.0 AOP 에러. 문제 해결 (1) | 2012.05.15 |
---|---|
Spring3.0 Tiles (1) | 2012.05.14 |
Spring3.0 View error filedown (0) | 2012.05.14 |
Spring3.0 MVC 웹요청 처리 (0) | 2012.05.14 |
Spring 3.0 AOP (0) | 2012.05.14 |
기본 세팅 프로젝트 파일
en_US
ko_KR
3. 국제화 LocaleReslover를 이용한 Locale 변경
국제화 LocaleChangeInterceptor
4.엑셀파일 다운로드 , PDF 다운로드
Spring3.0 Tiles (1) | 2012.05.14 |
---|---|
Spring3.0 DB (0) | 2012.05.14 |
Spring3.0 MVC 웹요청 처리 (0) | 2012.05.14 |
Spring 3.0 AOP (0) | 2012.05.14 |
Spring3.0 DI 3 (0) | 2012.05.14 |
3.예제 @RequestParam
Spring3.0 DB (0) | 2012.05.14 |
---|---|
Spring3.0 View error filedown (0) | 2012.05.14 |
Spring 3.0 AOP (0) | 2012.05.14 |
Spring3.0 DI 3 (0) | 2012.05.14 |
스프링 3.0 @ 어노테이션 기반 설정 (0) | 2012.05.14 |
05. 스프링 AOP
* AOP용어 *
Spring3.0 View error filedown (0) | 2012.05.14 |
---|---|
Spring3.0 MVC 웹요청 처리 (0) | 2012.05.14 |
Spring3.0 DI 3 (0) | 2012.05.14 |
스프링 3.0 @ 어노테이션 기반 설정 (0) | 2012.05.14 |
Spring3.0 message&event (1) | 2012.05.14 |
==================================이론======================================
*의존관계 자동 설정
2.프로퍼티 타입을 이용한 의존관계 자동설정
4. 서로 다른 범위 빈에 대한 의존 처리
<aop:scoped-proxy /> 처리
<aop:scoped-proxy /> 빼면 같아짐 Worker가 싱글턴이기 때문
5. 외부 설정 프로퍼티
Spring3.0 MVC 웹요청 처리 (0) | 2012.05.14 |
---|---|
Spring 3.0 AOP (0) | 2012.05.14 |
스프링 3.0 @ 어노테이션 기반 설정 (0) | 2012.05.14 |
Spring3.0 message&event (1) | 2012.05.14 |
Spring3.0 Di 2 (0) | 2012.05.14 |
04장. 어노테이션 기반 설정
@Required에 값을 안넣어주는경우.
Spring 3.0 AOP (0) | 2012.05.14 |
---|---|
Spring3.0 DI 3 (0) | 2012.05.14 |
Spring3.0 message&event (1) | 2012.05.14 |
Spring3.0 Di 2 (0) | 2012.05.14 |
Spring3.0 DI AOP (0) | 2012.05.14 |
메시지 및 이벤트 처리 - 국제화
Spring3.0 DI 3 (0) | 2012.05.14 |
---|---|
스프링 3.0 @ 어노테이션 기반 설정 (0) | 2012.05.14 |
Spring3.0 Di 2 (0) | 2012.05.14 |
Spring3.0 DI AOP (0) | 2012.05.14 |
스프링 3.0 강좌 (0) | 2012.05.11 |
chap01.zip chap02.zip
컨트롤+ 스페이스바 = 이클립스 단축키
==================================이론======================================
스프링 컨테이너
BeanFactory 인터페이스
<!-- List 타입 프로퍼티 설정 -->
<bean name="performanceMonitor" class="madvirus.spring.chap02.PerformanceMonitor">
<property name="deviations">
<list>
//ref 태그로 객체목록을 전달받는다.
<ref bean="monitor"/>
<ref bean="smsSender"/>
<bean class="madvirus.spring.chap02.HeaderFiter"/> //임의 객체를 List에 전달할수도있다.
</list>
</property>
</bean>
<bean id="monitor" class="madvirus.spring.chap02.SystemMonitor" />
<bean id="smsSender" class="madvirus.spring.chap02.SmsSender"/>
(3) Properties 타입 : 특별한 타입의 Map 으로 키와 값 모두 String 인 맵으로 보통 Properties 클래스는 환경변수나 설정정보와 같이 상황에 따라 변경되는 값을 저장하기 위한 용도로 주로 사용된다.
4. 콜렉션 타입 프로퍼티 설정 - List타입과 배열
스프링 3.0 @ 어노테이션 기반 설정 (0) | 2012.05.14 |
---|---|
Spring3.0 message&event (1) | 2012.05.14 |
Spring3.0 DI AOP (0) | 2012.05.14 |
스프링 3.0 강좌 (0) | 2012.05.11 |
스프링 3.0 동영상 강좌. (0) | 2012.05.09 |