'분류 전체보기'에 해당되는 글 2491건

  1. 2012.05.11 [이클립스, STS] maven-dependency-plugin (goals "copy-dependencies","unpack") is not supported by m2e
  2. 2012.05.10 인쇄시 res://ieframe.dll/preview.js 오류
  3. 2012.05.08 was 모니터링 툴 psi-probe
  4. 2012.05.08 was 모니터링 툴 psi-probe
  5. 2012.05.08 실시간으로 Apache Tomcat를 모니터(측정)링 하는것. 1
  6. 2012.05.08 Java jstat로 메모리 모니터링
  7. 2012.05.08 Jstat 으로 JVM heap memory 모니터링 하기
  8. 2012.05.08 JVM을 사용하여 디렉토리 프록시 서버에 대한 모니터링된 데이터 검색
  9. 2012.05.08 Java SE 6 플랫폼 응용 프로그램 모니터링 및 관리
  10. 2012.05.02 [Eclipse] 파일 또는 디렉토리를 버전관리 대상에서 제외하는 법
  11. 2012.05.02 이클립스 플러그인 - jreble로 웹서버 재부팅 없이 클래스 변경 적용하기 2
  12. 2012.05.02 [jrebel] 자바 클래스 변경시 서버 재기동 없이 적용하기
  13. 2012.05.02 사람을 위한 자동화: Eclipse 플러그인으로 코드 품질 높이기
  14. 2012.05.02 html5 한글명세서
  15. 2012.04.28 ItemRenderer 사용예
  16. 2012.04.27 다양한 ItemRenderer의 적용 (콤보박스, ComboBox편)
  17. 2012.04.27 iBATIS DynamicQuery 사용법
  18. 2012.04.27 [펌][iBatis] iBatis like, iBatis Dynamic SQL
  19. 2012.04.10 HIBERNATE - 개성있는 자바를 위한 관계 영속
  20. 2012.04.10 Unable to Start due to GenericJDBCException Cannot open Connection Error
  21. 2012.04.09 ScriptX printing: technical manual
  22. 2012.03.26 oracle 채번
  23. 2012.03.26 Group By 에서 문자열 합치기 - 버전별 정리
  24. 2012.03.16 집합 쿼리(UNION, INTERSECT, MINUS)
  25. 2012.03.15 javascript close 사용시 안내문구 없애는 방법
  26. 2012.03.15 ERWin 재설치 오류 및 삭제시 오류
  27. 2012.03.13 iBatis 예제 - 1 (iBatis 기본설정 및 데이터 출력)
  28. 2012.03.12 [펌] node.js와 express설치 정리..
  29. 2012.03.12 node.js는 무엇인가? #2 : Hello World 실행하기
  30. 2012.03.12 node.js 따라하기
98..Etc/Etc...2012. 5. 11. 00:07
반응형

출처 :  http://knight76.tistory.com/archive/20120112




 

m2 eclipse plugin이 1.0 버전 업하면서 생긴 단순한 설정은 아래와 같이 처리한다.
http://knight76.tistory.com/entry/이클립스-STS-maven-builder-변경


컴파일을 잘 되는데, pom.xml 파일에 maven parent를 사용하는 부분에서 에러가 있다고 나온다. build life cycle에서 무엇인가 이슈가 있다.

 

원인을 찾아보니, 이클립스 싸이트의 m2e 플러그인에 대한 내용이 있다. 간단히 요약해보면 다음과 같다. 빌드시 명시적으로 문제의 소지가 있는 플러그인에 대해서 에러로 처리할테니, 무시하든지 추가하든지 하는 설정을 넣으라는 얘기이다. (m2eclipse 플러그인 개발자도 maven 때문에 고생한다…. )

http://wiki.eclipse.org/M2E_plugin_execution_not_covered

https://issues.sonatype.org/browse/MNGECLIPSE-823에 내용에 있는 것처럼 리소스들과 컴파일이 안되는 문제가 발생되기도 했다. 0.12 버전 이하에서는 이클립스 빌드시 maven을 사용해서 컴파일을 했었다. 사실 이클립스 플러그인 개발입장에서는 그저 maven에 위임하는데, 어떤 “ Plug excution”이 동작하여 예상치 못하게 파일(리소스)가 날아가(missing) 버리거나 JVM, OS 리소스 부족으로 문제를 일으키는 경우가 있었다.

이 문제를 해결해가 위해서 1.0 부터는 빌드 lifecycle에 명확한 방법(explicit instructions)을 제공하였다. 이것을 “project build lifecycle mapping” (lifecycle mapping)이라고  한다. pom.xml 설정에 maven 빌드와 별도로플러그 실행(execution)에 대한 정보를 넣을 수 있게 하였다.

예를 들어 project build lifecycle mapping 정보가 없는 경우에 대해서는 다음과 같이 m2 이클립스 플러그인에서 에러로 처리한다고 한다.

Plugin execution not covered by lifecycle configuration:
org.apache.maven.plugins:maven-antrun-plugin:1.3:run
    (execution: generate-sources-input, phase: generate-sources)
이 문제를 해결하기 위해서 ignore 또는 execute goal을 넣어야 한다. 

 

아래 에러 로그에 있는 내용이 바로 위에 작성한 위키의 내용과 일치한다.

Multiple annotations found at this line: 
    - Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:xml-maven-plugin:1.0:transform 
     (execution: default, phase: process-resources) 
    - Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.3:run 
     (execution: process-resources, phase: process-resources) 
    - maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e. 
    - Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.3:run 
     (execution: copy-base-resource, phase: generate-sources)

 

이 방식을 이용해서 아래와 같이 pom.xml 파일에 정리하였더니 더 이상 이클립에서 에러라고 처리되지 않는다.

<build> 
        <pluginManagement> 
            <plugins> 
                <!--This plugin's configuration is used to store Eclipse m2e settings 
                    only. It has no influence on the Maven build itself. --> 
                <plugin> 
                    <groupId>org.eclipse.m2e</groupId> 
                    <artifactId>lifecycle-mapping</artifactId> 
                    <version>1.0.0</version> 
                    <configuration> 
                        <lifecycleMappingMetadata> 
                            <pluginExecutions> 
                                <pluginExecution> 
                                    <pluginExecutionFilter> 
                                        <groupId> 
                                            org.apache.maven.plugins 
                                        </groupId> 
                                        <artifactId> 
                                            maven-antrun-plugin 
                                        </artifactId> 
                                        <versionRange> 
                                            [1.3,) 
                                        </versionRange> 
                                        <goals> 
                                            <goal>run</goal> 
                                        </goals> 
                                    </pluginExecutionFilter> 
                                    <action> 
                                        <ignore></ignore> 
                                    </action> 
                                </pluginExecution> 
                                <pluginExecution> 
                                    <pluginExecutionFilter> 
                                        <groupId> 
                                            org.codehaus.mojo 
                                        </groupId> 
                                        <artifactId> 
                                            xml-maven-plugin 
                                        </artifactId> 
                                        <versionRange> 
                                            [1.0,) 
                                        </versionRange> 
                                        <goals> 
                                            <goal>transform</goal> 
                                        </goals> 
                                    </pluginExecutionFilter> 
                                    <action> 
                                        <ignore></ignore> 
                                    </action> 
                                </pluginExecution> 
                                <pluginExecution> 
                                    <pluginExecutionFilter> 
                                        <groupId>org.apache.maven.plugins</groupId> 
                                        <artifactId>maven-dependency-plugin</artifactId> 
                                        <versionRange>[1.0.0,)</versionRange> 
                                        <goals> 
                                            <goal>copy-dependencies</goal> 
                                        </goals> 
                                    </pluginExecutionFilter> 
                                    <action> 
                                        <ignore /> 
                                    </action> 
                                </pluginExecution> 
                            </pluginExecutions> 
                        </lifecycleMappingMetadata> 
                    </configuration> 
                </plugin> 
            </plugins> 
        </pluginManagement> 
    </build>

Posted by 1010
98..Etc/Etc...2012. 5. 10. 21:05
반응형
인쇄시 res://ieframe.dll/preview.js 오류

인쇄시 res://ieframe.dll/preview.js 오류

Windows 7 32bit
IE 9.0.8112.16421

IE에서 인쇄시 아래와 같은 오류가 발생합니다.
---------------------------------------------
이 페이지의 스크립트에서 오류가 발생하였습니다.
줄 : 1527
문자 : 1
오류 : 잘못된 인수입니다.
코드 : 0
URL : res://ieframe.dll/preview.js
---------------------------------------------


조치
1. 프린터 재설치
2. Regsvr32.exe Ole32.dll 등 실행
3. 바이러스 검사 실시
4. IE9 삭제 후 IE8에서도 같은 오류 -> IE9 재설치 이후에도 같은 오류 발생
5. 시작프로그램 및 타사 서비스 해제
6. 툴바 사용안함
7. 레지스트리 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects 등 삭제

모두 다 해봤는데도 여전히 같은 문제가 발생합니다.
심지어 설치 프린터를 모두 삭제한 이후에도 해당 문제가 발생합니다.

기타 브라우저(크롬, firefox) 및 여타 응용 프로그램에서는 정상적으로 프린트가 됩니다.
오직 IE에서만 위 오류가 나면서 인쇄가 되지 않습니다.
    • 아동 착취 또는 학대
    • 희롱 또는 위협
    • 부적절한/성인용 콘텐츠
    • 노출
    • 모독
    • 소프트웨어 불법 복제
    • 스팸/광고
    • 바이러스/스파이웨어/맬웨어 위험
    • 기타 사용 약관 또는 준수 사항 위반
1이 질문을 올린
사람 수

이 게시물이 유용했습니까?

1

투표

답변

안녕하세요.

이와 같은 문제는 Internet Explorer 9 구동에 필요한 관련 모듈이 올바르게 작동하지 못해 발생한 증상 입니다.

아래 스크립트를 이용하여 Internet Explorer 에 사용되는 system libraries (dll) 의 레지스트리 스크립트 손상을 복구해 보시기 바랍니다.

  1. [시작 - 모든 프로그램 - 보조 프로그램 - 메모장]을 열고 아래 스크립트를 모두 복사하여 붙여 넣기 한 후 바탕화면에 " rereg.cmd " 이름으로 파일을 저장 합니다.
  2. 바탕화면에 저장 된 rereg.cmd 파일을 실행 합니다.
  3. 컴퓨터 다시 시작 합니다.

스크립트 시작 ----------- (아래 줄 부터 복사 합니다)

@echo off
echo.
echo IEREREG Version 1.07 for IE8 27.03.2009
echo by Kai Schaetzl http://iefaq.info
echo installs and registers (if suitable) all DLLs known to be used by IE8.
echo should only take a few seconds, but please be patient
echo.
REM ******************************
echo registering IE files
REM IE files (= part of setup)
regsvr32 /s /i browseui.dll
REM regsvr32 /s /i browseui.dll,NI (unnecessary)
regsvr32 /s corpol.dll
regsvr32 /s dxtmsft.dll
regsvr32 /s dxtrans.dll
REM simple HTML Mail API
regsvr32 /s "%ProgramFiles%\internet explorer\hmmapi.dll"
REM group policy snap-in
regsvr32 /s ieaksie.dll
REM smart screen
regsvr32 /s ieapfltr.dll
REM ieak branding
regsvr32 /s iedkcs32.dll
REM dev tools
regsvr32 /s "%ProgramFiles%\internet explorer\iedvtool.dll"
regsvr32 /s iepeers.dll
REM Symptom: IE8 closes immediately on launch, missing from IE7
regsvr32 /s "%ProgramFiles%\internet explorer\ieproxy.dll"
REM no install point anymore
REM regsvr32 /s /i iesetup.dll
REM no reg point anymore
REM regsvr32 /s imgutil.dll
regsvr32 /s /i /n inetcpl.cpl
REM no install point anymore
REM regsvr32 /s /i inseng.dll
regsvr32 /s jscript.dll
REM license manager
regsvr32 /s licmgr10.dll
REM regsvr32 /s msapsspc.dll
REM regsvr32 /s mshta.exe
REM VS debugger
regsvr32 /s msdbg2.dll
REM no install point anymore
REM regsvr32 /s /i mshtml.dll
regsvr32 /s mshtmled.dll
regsvr32 /s msident.dll
REM no reg point anymore
REM regsvr32 /s msrating.dll
REM multimedia timer
regsvr32 /s mstime.dll
REM no install point anymore
REM regsvr32 /s /i occache.dll
REM process debug manager
regsvr32 /s "%ProgramFiles%\internet explorer\pdm.dll"
REM no reg point anymore
REM regsvr32 /s pngfilt.dll
REM regsvr32 /s /i setupwbv.dll (not there anymore!)
regsvr32 /s tdc.ocx
regsvr32 /s /i urlmon.dll
REM regsvr32 /s /i urlmon.dll,NI,HKLM
regsvr32 /s vbscript.dll
REM VML renderer
regsvr32 /s "%CommonProgramFiles%\microsoft shared\vgx\vgx.dll"
REM no install point anymore
REM regsvr32 /s /i webcheck.dll
regsvr32 /s /i /n wininet.dll
REM ******************************
echo registering system files
REM additional system dlls known to be used by IE
REM added 11.05.2006 Symptom: Add-Ons-Manager menu entry is present but nothing happens
regsvr32 /s extmgr.dll
REM added 12.05.2006 Symptom: Javascript links don't work (Robin Walker) .NET hub file
regsvr32 /s mscoree.dll
REM added 23.03.2009 Symptom: Find on this page is blank
regsvr32 /s oleacc.dll
REM added 24.03.2009 Symptom: Printing problems, open in new window
regsvr32 /s ole32.dll
REM mscorier.dll
REM mscories.dll
REM Symptom: open in new tab/window not working
regsvr32 /s actxprxy.dll
regsvr32 /s asctrls.ocx
regsvr32 /s cdfview.dll
regsvr32 /s comcat.dll
regsvr32 /s /i /n comctl32.dll
regsvr32 /s cryptdlg.dll
regsvr32 /s /i /n digest.dll
regsvr32 /s dispex.dll
regsvr32 /s hlink.dll
regsvr32 /s mlang.dll
regsvr32 /s mobsync.dll
regsvr32 /s /i msieftp.dll
REM regsvr32 /s msnsspc.dll #no entry point
regsvr32 /s msr2c.dll
regsvr32 /s msxml.dll
regsvr32 /s oleaut32.dll
REM regsvr32 /s plugin.ocx #no entry point
regsvr32 /s proctexe.ocx
REM plus DllRegisterServerEx ExA ExW ... ?
regsvr32 /s /i scrobj.dll
REM shdocvw.dll hasn't been updated for IE7 and IE8, it still registers itself for the Windows Internet Controls
regsvr32 /s /i shdocvw.dll
regsvr32 /s sendmail.dll
REM ******************************
REM PKI/crypto functionality
REM initpki can take very long to run and is rarely a problem
REM if there are problems with crypto, SSL, certificates
REM remove the three following REMs from the lines
REM echo We are almost done except one crypto file
REM echo but this will take very long, be patient!
REM regsvr32 /s /i:A initpki.dll
REM ******************************
REM tabbed browser, do at the end, why originally with /n ?
regsvr32 /s /i ieframe.dll
REM ******************************
echo correcting bugs in the registry
REM do some corrective work
REM Symptom: new tabs page cannot display content because it cannot access the controls (added 27. 3.2009)
REM This is a result of a bug in shdocvw.dll (see above), probably only on Windows XP
reg add "HKCR\TypeLib\{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}\1.1\0\win32" /ve /t REG_SZ /d %systemroot%\system32\ieframe.dll /f
REM ******************************
echo all tasks have been finished
echo.
pause

스크립트 종료 --------- ( 위에 줄 까지 복사 합니다 )

응답이 문제 해결에 도움이 되었다면, 아래에 있는 답변으로 [표시]버튼을 눌러 주시기 바랍니다. 이는 유사한 증상을 겪는 다른 사용자들에게 도움이 될 수 있습니다.

문제가 계속 지속되거나진행이 어려운 경우마이크로소프트 기술지원 1577-9700(내선 3-1)으로문의하시기 바랍니다.

* 참고: 라이선스 보증기간 등에 의해무상 또는 유상지원이 있습니다

Posted by 1010
카테고리 없음2012. 5. 8. 15:41
반응형

1. psi-probe 


 

1. 다운로드 :  http://code.google.com/p/psi-probe/  

2. 설정 : tomcat 의 /conf/tomcat-users.xml 편집

<role rolename="manager" />
<role rolename="admin" />  
<user username="admin" password="xxx" roles="manager,admin" />
 
3. 설치 : 다운로드 받은 probe.war 를  tomcat의 webapps 폴더로 복수 후 재가동 한다.

4. 실행 : http://~/probe 로 접속 후 2번에서 추가한 아이디와 패스워드로 로긴 후 사용

5. 참고 사이트 


Posted by 1010
카테고리 없음2012. 5. 8. 15:33
반응형

  • 톰캣 5.5까지만 해도 Tomcat Admin 이라 하여 JNDI나 Deploy를 쉽게 설정할 수 있도록 만든 툴이 있었는데, 현재는 없다. 톰캣 6부터는 개발이 중단되었다. (앞으로 개발 계획도 없다) 톰캣 어드민으로 쓸만한 프로그램인 Psi-Probe를 소개한다.
  • 20009년까지만 해도 Lambda Probe라는 툴이 많이 쓰였는데 개발이 중단되었다. Psi Probe는 람다 프로브를 이어 받은 프로그램이다.
  • 설치방법

    1. psi-probe홈페이지에 가서 probe-2.3.0.zip를 다운로드 받고 압축을 풀어 probe.war를 얻는다. 2.3 부터 톰캣 7을 공식지원한다.
    2. Tomcat Manager에 접속(http://localhost:8080/manager/html, 암호는 tomcat-users.xml 에서 설정해준 암호를 넣으면 된다. 솔라나라에서는 tomcat / s3cret 를 사용한다)해서 화면 하단의 [WAR file to deploy]에서 probe.war를 선택하고 Deploy를 클릭한다.
    3. 상단의 [Applications]에 [/probe]가 추가될 것이다. http://localhost:8080/probe/ 에 접속한다. 암호는 Tomcat Manager 암호와 같다.
    4. 아래와 유사한 화면을 볼 수 있을 것이다.
      - 어플리케이션 정보
      어플리케이션
      - 시스템 정보 - 개요
      시스템 정보- 개요
      - 시스템 정보 - 메모리
      시스템 정보- 메모리
      - 시스템 정보 - 운영체제
      시스템 정보- 운영체제
      - 접속 정보
      접속 정보

Posted by 1010
98..Etc/Tomcat2012. 5. 8. 15:11
반응형

자세한 히스토리는 모르겠지만 Tomcat 모니터링 툴인 Lambda Probe의 개발이 중단되고, 현재는 구글에서 PSI Probe로 계속 진행이 되고 있습니다.
http://code.google.com/p/psi-probe/ 이 사이트에 가면 다운로드 및 설치 매뉴얼이 있으니참조하시기 바랍니다.

설치

  1. 최신 버전을 다운로드 받으신 후 압축을 풀면  probe.war 파일이 생성됩니다.
  2. Tomcat의 Manager GUI에 접속하셔서 War file to deploy에 probe.war 파일을 선택하고 deploy 버튼을 누르면 자동으로 Application이 설치가 됩니다.

    deploy probe

    deploy probe

  3. tomcat_home/webapps에 보시면 probe라는 디렉토리가 생성이 되어 있는걸 확인할 수 있습니다.
  4. http://domain_name/probe 에 접속해서 tomcat-users.xml에 설정한 manager의 id/pwd로 접속하여 사용하면 됩니다.
probe

probe

상단 메뉴->System Information 을 클릭한 후, 우측메뉴-> memory utilization을 클릭하면
아래와 같이 JVM memory 상태를 확인할 수 있다.
 




출처: http://dukeom.wordpress.com/2011/08/08/psi-probe-tomcat-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81-%ED%88%B4/

Posted by 1010
01.JAVA/Java2012. 5. 8. 15:03
반응형

출처 : http://5dol.tistory.com/182

우선 간단히 확인하면 아래처럼 나온다. jstat -옵션 -pid -시간 하면 된다.
ex) ~]jstat -gc 16543 1000

저건 pid 16543(java)를 1초에 한번씩 결과값을 보여달란거다. 

pid는 ps -efw | grep java로 알아내면 된다. 

~] jstat --help

 invalid argument count
Usage: jstat -help|-options
       jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

Definitions:
  <option>      An option reported by the -options option
  <vmid>        Virtual Machine Identifier. A vmid takes the following form:
                     <lvmid>[@<hostname>[:<port>]]
                Where <lvmid> is the local vm identifier for the target
                Java virtual machine, typically a process id; <hostname> is
                the name of the host running the target Java virtual machine;
                and <port> is the port number for the rmiregistry on the
                target host. See the jvmstat documentation for a more complete
                description of the Virtual Machine Identifier.
  <lines>       Number of samples between header lines.
  <interval>    Sampling interval. The following forms are allowed:
                    <n>["ms"|"s"]
                Where <n> is an integer and the suffix specifies the units as
                milliseconds("ms") or seconds("s"). The default units are "ms".
  <count>       Number of samples to take before terminating.
  -J<flag>      Pass <flag> directly to the runtime system.



옵션은 다음과 같다.

 옵션명내용 
 class 클래스 로더의 동작에 관한 통계 데이터
 compiler HotSpot Just-in-Time 컴파일러의 동작에 관한 통계 데이터
 gc 가베지 컬렉트된 heap의 동작에 관한 통계 데이터
 gccapactiy 세대마다의 용량과 대응하는 영역에 관한 통계 데이터
 gccause 가베지 콜렉션 통계 데이터의 개요 (-gcutil 와 같다)와 직전 및 현재 (적용 가능한 경우)의 가베지 콜렉션 이벤트의 원인
 gcnew New 세대의 동작에 관한 통계 데이터
 gcnewcapacity New 세대의 사이즈와 대응하는 영역에 관한 통계 데이터
 gcold Old 세대 및 Permanent 세대의 동작에 관한 통계 데이터
 gcoldcapacity Old 세대의 사이즈에 관한 통계 데이터
 gcpermcapacity Permanent 세대의 사이즈에 관한 통계 데이터
 gcutil 가베지 콜렉션 통계 데이터의 개요
 printcompilationHotSpot 컴파일 방법의 통계 데이터

각 옵션에 대한 컬럼에 대한 설명은 다음과 같다.

-class  클래스 로더의 통계 데이터
 Loaded Bytes Unloaded Bytes Time
 로드 된 클래스의 수 로드 된 K 바이트수 언로드된 클래스의 수 언로드된 K 바이트수 클래스의 로드나 언로드 처리에 필요로 한 시간

-compiler HotSpot Just-In-Time 컴파일러의 통계 데이터
 Compiled Failed Invalid Time FailedType FailedMethod
 실행된 컴파일 태스크의 수 실패한 컴파일 태스크의 수 무효로 된 컴파일 태스크의 수 컴파일 태스크의 실행에 필요로 한 시간 마지막에 실패한 컴파일의 컴파일 타입 마지막에 실패한 컴파일의 클래스명과 메소드

-gc 가비지 컬렉트된 heap의 통계 데이터
 컬럼명 설명
 S0C Survivor 영역 0 의 현재의 용량 (KB)
 S1C Survivor 영역 1 의 현재의 용량 (KB)
 S0U Survivor 영역 0 의 사용율 (KB)
 S1U Survivor 영역 1 의 사용율 (KB)
 EC Eden 영역의 현재의 용량 (KB)
 EU Eden 영역의 사용율 (KB)
 OC Old 영역의 현재의 용량 (KB)
 OU Old 영역의 사용율 (KB)
 PC Permanent 영역의 현재의 용량 (KB)
 PU Permanent 영역의 사용율 (KB)
 YGC Young 세대의 GC 이벤트수
 YGCT Young 세대의 가베지 콜렉션 시간
 FGC 풀 GC 이벤트수
 FGCT 풀 가베지 콜렉션 시간
 GCT 가베지 콜렉션의 합계 시간

-gccapacity 메모리프르 세대 및 영역 용량

 컬럼명설명 
 NGCMN New 세대의 최소 용량 (KB)
 NGCMX New 세대의 최대 용량 (KB)
 S0C Survivor 영역 0 의 현재의 용량 (KB)
 S1C Survivor 영역 1 의 현재의 용량 (KB)
 EC Eden 영역의 현재의 용량 (KB)
 OGCMN Old 세대의 최소 용량 (KB)
 OGCMX Old 세대의 최대 용량 (KB)
 OGC Old 세대의 현재의 용량 (KB)
 OC Old 영역의 현재의 용량 (KB)
 PGCMN Permanent 세대의 최소 용량 (KB)
 PGCMX Permanent 세대의 최대 용량 (KB)
 PGC Permanent 세대의 현재의 용량 (KB)
 PC Permanent 영역의 현재의 용량 (KB)
 YGC Young 세대의 GC 이벤트수
 FGC 풀 GC 이벤트수
 NGC New 세대의 현재의 용량 (KB)

-gcutil 가베지 콜렉션 통계 데이터의 개요
 컬럼명 설명
 S0 Survivor 영역 0 의 사용율 (현재의 용량에 대한 퍼센티지)
 S1 Survivor 영역 1 의 사용율 (현재의 용량에 대한 퍼센티지)
 E Eden 영역의 사용율 (현재의 용량에 대한 퍼센티지)
 O Old 영역의 사용율 (현재의 용량에 대한 퍼센티지)
 P Permanent 영역의 사용율 (현재의 용량에 대한 퍼센티지)
 YGC Young 세대의 GC 이벤트수
 YGCT Young 세대의 가베지 콜렉션 시간
 FGC 풀 GC 이벤트수
 FGCT 풀 가베지 콜렉션 시간
 GCT 가베지 콜렉션총시간

-gccause GC 이벤트를 포함한 가베지 콜렉션 통계 데이터(gcutil에 두개 컬럼이 추가됨)
 컬럼명 설명
 LGCC 마지막 가베지 콜렉션의 원인
 GCC 현재의 가베지 콜렉션의 원인

-gcnew New 세대의 통계 데이터
 컬럼명 설명
 S0C Survivor 영역 0 의 현재의 용량 (KB)
 S1C Survivor 영역 1 의 현재의 용량 (KB)
 S0U Survivor 영역 0 의 사용율 (KB)
 S1U Survivor 영역 1 의 사용율 (KB)
 TT 전당 들어가 귀의치
 MTT 최대 전당 들어가 귀의치
 DSS 적절한 Survivor 사이즈 (KB)
 EC Eden 영역의 현재의 용량 (KB)
 EU Eden 영역의 사용율 (KB)
 YGC Young 세대의 GC 이벤트수
 YGCT Young 세대의 가베지 콜렉션 시간

-gcold 옵션 Old 및 Permanent 세대의 통계 데이터
 컬럼명설명 
 PC Permanent 영역의 현재의 용량 (KB)
 PU Permanent 영역의 사용율 (KB)
 OC Old 영역의 현재의 용량 (KB)
 OU Old 영역의 사용율 (KB)
 YGC Young 세대의 GC 이벤트수
 FGC 풀 GC 이벤트수
 FGCT 풀 가베지 콜렉션 시간
 GCT 가베지 콜렉션총시간

-gcoldcapacity Old 세대의 통계 데이터
 컬럼명설명 
 OGCMN Old 세대의 최소 용량 (KB)
 OGCMX Old 세대의 최대 용량 (KB)
 OGC Old 세대의 현재의 용량 (KB)
 OC Old 영역의 현재의 용량 (KB)
 YGC Young 세대의 GC 이벤트수
 FGC 풀 GC 이벤트수
 FGCT 풀 가베지 콜렉션 시간
 GCT 가베지 콜렉션총시간

-printcompilation HotSpot 컴파일 방법의 통계 데이터

 컬럼명설명 
 Compiled 실행된 컴파일 태스크의 수
 Size 메소드의 바이트 코드의 바이트수
 Type 컴파일 타입
 Method 컴파일 방법을 특정하는 클래스명과 메소드명. 클래스명에서는, 이름 공간의 단락 문자로서 「.」(은)는 아니고 「/」이 사용된다. 메소드명은, 지정된 클래스내의 메소드이다. 이러한 2 개의 필드의 형식은, HotSpot -XX:+PrintComplation 옵션과 대응하고 있다


사용 방법

jstat -gcutil -h5 16543 1000 10

jstat를 -gcutil 옵션을 주고 5개씩 출력마다 헤더를 출력(h5)하고 1초마다 출력하되 10개씩 보여준다.

Posted by 1010
01.JAVA/Java2012. 5. 8. 15:01
반응형


1. jstat 수행 방법
   - 우선 모니터링 하고자 하는 프로세스의 ID 를 확인합니다.
      확인하는 방법은 ps -ef | grep java 로 확인을 해도 되고, 프롬프트 상태에서 jps 라고 입력한 뒤 엔터를 치면 해당 JVM에서 수행된 프로세스의 ID를 보여줍니다.
      (jps 사용시에는 PATH에 해당 JDK가 설정되어 있어야 합니다.
 
 

  - 두번째로 jstat 명령을 수행 합니다.

      jstat -gcutil -h20 -t 7251 3000 3000

      -> gcutil : gcutil 에 대해서 수행

      -> -h20 : 20라인마다 header 찍음

      -> -t : time stamp 프린트(JVM 이 스타트 된 이후의 시간)

      -> 7251 : 프로세스 id

      -> 3000 : interval (ms 단위)

      -> 3000 : count
 
 - 수행 결과
 
2. 각각의 항목 설명

  - S0 Survivor 영역 0 의 사용율 (현재의 용량에 대한 퍼센티지)

  - S1 Survivor 영역 1 의 사용율 (현재의 용량에 대한 퍼센티지)

  - Eden 영역의 사용율 (현재의 용량에 대한 퍼센티지)

  - Old 영역의 사용율 (현재의 용량에 대한 퍼센티지)

  - Permanent 영역의 사용율 (현재의 용량에 대한 퍼센티지)

  - YGC Young 세대의 GC 이벤트수

  - YGCT Young 세대의 가베지 콜렉션 시간

  - FGC 풀 GC 이벤트수

  - FGCT 풀 가베지 콜렉션 시간

  - GCT : 가베지 콜렉션총시간
 
3. 샘플
  >jstat -gcutil 21891 250 7
      S0     S1     E      O      P     YGC    YGCT    FGC    FGCT     GCT
     12.44   0.00  27.20   9.49  96.70    78    0.176     5    0.495    0.672
     12.44   0.00  62.16   9.49  96.70    78    0.176     5    0.495    0.672
     12.44   0.00  83.97   9.49  96.70    78    0.176     5    0.495    0.672
      0.00   7.74   0.00   9.51  96.70    79    0.177     5    0.495    0.673
      0.00   7.74  23.37   9.51  96.70    79    0.177     5    0.495    0.673
      0.00   7.74  43.82   9.51  96.70    79    0.177     5    0.495    0.673
      0.00   7.74  58.11   9.51  96.71    79    0.177     5    0.495    0.673

 

    이 예의 출력은, Young 세대의 콜렉션이 3 번째와 4 번째의 샘플간에 행해진 것을 나타내고 있습니다.

    콜렉션에는 0.001 초 걸리고 있어 오브젝트가 Eden 영역 (E)으로부터 Old 영역 (O)에 승격했기 때문에,

    Old 영역의 사용율은 9.49% 에서 9.51% 에 증가하고 있습니다.

    Survivor 영역은, 콜렉션전은 12.44% 가 사용되고 있었습니다만, 콜렉션 후는 7.74% 밖에 사용되고 있지 않습니다.

 

실시간으로 메모리 사용을 좀 확인해야 하는 상황에서는 위와 같이 jstat 로 간단하게 모니터링을 수행하면

현재의 JVM 메모리 사용 상황을 확인이 가능할 것 같습니다.

 

가장 정확한 건 GC 로그를 별도의 파일로 출력하게 해서 분석하는 것이지만, 이럴 경우에는 실시간으로 확인이 힘들기 때문에

위와 같이 사용하는 것도 괜찮은 방법 중의 하나일 것 같습니다.

물론 JVM 에 계속 request 를 보내기 때문에 부하가 있을 듯 하지만, 지금 생각으로는 크게 영향은 미치지 않을 듯 하네요..

영향이 고려되면 interval을 좀 조정하든지 하면 될 듯 합니다.

Posted by 1010
01.JAVA/Java2012. 5. 8. 15:00
반응형

JVM을 사용하여 디렉토리 프록시 서버에 대한 모니터링된 데이터 검색

디렉토리 프록시 서버는 JVM(Java Virtual Machine) 내에서 실행되고 JVM 시스템의 메모리에 따라 달라집니다. 디렉토리 프록시 서버가 올바르게 실행되고 있는지 확인하려면 JVM 시스템의 메모리 사용을 모니터링해야 합니다.

JVM 시스템의 매개 변수를 조정하는 방법에 대한 자세한 내용은 Sun Java System Directory Server Enterprise Edition 6.0 Deployment Planning Guide의 Hardware Sizing For Directory Proxy Server을 참조하십시오.

기본적으로 JVM 시스템의 힙 크기는 250MB입니다. 디렉토리 프록시 서버에 물리적 메모리가 충분하지 않은 경우 힙 크기는 250MB보다 작을 수 있습니다.

디렉토리 프록시 서버가 실행 중인 경우 JVM 시스템의 힙 크기를 모니터링하여 메모리가 부족해지지 않도록 할 수 있습니다. 이렇게 하려면 JDK(Java Development Kit)와 함께 제공되는 표준 도구를 사용합니다. 이러한 도구는 $JAVA_HOME/bin/jps 및 $JAVA_HOME/bin/jstat 디렉토리에 있습니다.

ProcedureJVM의 힙 크기를 보려면

DSCC를 사용하여 이 작업을 수행할 수 없습니다. 이 절차에 설명된 것처럼 명령줄을 사용하십시오.

    JVM의 힙 크기를 봅니다.


    $ dpadm get-flags instance-path jvm-args
    jvm-args: -Xms250M  -Xmx250M

Procedure디렉토리 프록시 서버가 실행 중인 경우 JVM의 힙 크기를 모니터링하려면

DSCC를 사용하여 이 작업을 수행할 수 없습니다. 이 절차에 설명된 것처럼 명령줄을 사용하십시오.

  1. 디렉토리 프록시 서버 인스턴스의 PID를 봅니다.


    $ jps
  2. JVM 시스템에 사용된 메모리를 봅니다.


    $ jstat -gcutil PID
    
    • 0 열이 거의 100%에 도달하면 JVM 시스템에 메모리가 부족한 것입니다.

    • FGC는 전체 가비지 컬렉션(GC) 이벤트 수입니다. 가비지 컬렉션은 광범위합니다.

    • GCT(Garbage Collection Time)는 GC에 사용된 시간입니다.

Posted by 1010
01.JAVA/Java2012. 5. 8. 14:59
반응형

BigAdmin System Administration Portal
Java SE 6 플랫폼 응용 프로그램 모니터링 및 관리
Print-friendly VersionPrint-friendly Version

번역 책임의 한계: 
본 기사는 어느 정도의 인간의 간섭과 사후 편집을 포함하여 컴퓨터 소프트웨어 프로그램으로 번역되었습니다. 번역은 독자의 편리함을 위해 “있는 그대로” 제공되며, Sun은 번역된 문장 또는 페이지 전체로서의 정확성 또는 완전성에 대한 아무런 대표성이 없으며 어떠한 책임도 지지 않습니다. 사이트와 툴의 사용에 관한 추가 고지 사항에 대해서는 본 사이트의 이용 약관을 참조하십시오.

 
 

기사 색인

응용 프로그램이 원래 속도보다 느리게 실행되거나 이전보다 느리게 실행되는 듯 하거나 또는 응용 프로그램이 응답이 없거나 중단되었습니다. 프로덕션 환경 또는 개발 중에 이러한 상황에 처할 수 있습니다. 이러한 문제의 원인은 무엇일까요? 흔히 메모리 누출, 교착 상태 및 동기화 문제와 같은 원인은 진단하기 어렵습니다. Java Platform Standard Edition(Java SE) 버전 6은 즉시 사용할 수 있는 모니터링 및 관리 기능을 제공하여 여러 일반적인 Java SE 문제를 진단할 수 있도록 도와줍니다.

이 기사는 Java SE 6 응용 프로그램을 모니터링 및 관리하는 단기 과정입니다. 첫 번째, Java SE 응용 프로그램의 일반적인 문제와 증상에 대해 설명합니다. 두 번째, Java SE 6의 모니터링 및 관리 기능의 개요에 대해 설명합니다. 세 번째, 다양한 JDK(Java Development Kit) 도구를 사용하여 이러한 문제를 진단하는 방법에 대해 설명합니다.

주: Java SE 플랫폼 사양에 대한 API 추가 또는 기타 개선 사항은 JSR 270 전문가 그룹에 의해 검토 및 승인됩니다.

Java SE 응용 프로그램의 일반적인 문제

일반적으로 Java SE 응용 프로그램의 문제는 메모리, 스레드, 클래스 및 잠금과 같은 중요 자원과 관련되어 있습니다. 자원 경합 또는 누수는 성능 문제나 예상치 않은 오류로 이어질 수 있습니다. 표 1은 Java SE 응용 프로그램의 몇 가지 일반적인 문제와 증상을 요약하고 개발자가 각 문제의 원인을 진단하는 데 도움을 줄 수 있는 도구를 나열합니다.

표 1. 일반적인 문제 진단 도구
 
 
문제
증상
진단 도구
OutOfMemoryError
메모리 사용 증가
빈번한 가비지 컬렉션
 
성장률이 높은 클래스
예상치 않은 수의 인스턴스가 있는 클래스
메모리 맵(jmap)
jmap -histo 옵션 참조
 
객체가 의도하지 않게 참조되고 있음
jconsole 또는 jmap(jhat 포함)
jmap -dump 옵션 참조
객체가 종료 대기 중임
jconsole
jmap -dump(jhat 포함)
객체 모니터의 스레드 블록 또는 java.util.concurrent 잠금
스레드 CPU 시간이 지속적으로 증가
jconsole(JTop 포함)
치열한 경합 통계가 있는 스레드
jconsole

메모리 부족

JVM(Java Virtual Machine)*에는 비힙 및 기본 유형의 메모리가 있습니다.

힙 메모리는 모든 클래스 인스턴스 및 배열이 할당되는 메모리의 런타임 데이터 영역입니다. 비힙 메모리에는 JVM의 최적화 또는 내부 처리에 필요한 메소드 영역과 메모리가 포함되어 있습니다. 이는 런타임 상수 풀, 필드 및 메소드 데이터, 메소드 및 구성자의 코드와 같은 클래스당 구조를 저장합니다. 기본 메모리는 운영 체제에 의해 관리되는 가상 메모리입니다. 응용 프로그램을 할당하기에 메모리가 부족한 경우 java.lang.OutOfMemoryError가 발생합니다.

다음은 각 메모리 유형에서의 OutOfMemoryError에 대한 가능한 오류 메시지입니다.

  • 힙 메모리 오류. 응용 프로그램이 새 객체를 만들지만 힙이 충분한 공간을 가지지 않고 더 이상 확장할 수 없을 경우 다음 오류 메시지와 함께 OutOfMemoryError가 발생합니다.

    java.lang.OutOfMemoryError: Java heap space
     
  • 비힙 메모리 오류. 영구 생성은 인턴된 문자열뿐만 아니라 클래스당 구조를 저장하는 핫스폿 VM 구현에 있는 비힙 메모리 영역입니다. 영구 생성이 가득 차면 응용 프로그램이 클래스 로드나 인턴된 문자열 할당에 실패하여 다음 오류 메시지와 함께 OutOfMemoryError가 발생합니다.

    java.lang.OutOfMemoryError: PermGen space
    
     
  • 기본 메모리 오류. 응용 프로그램의 JNI(Java Native Interface) 코드 또는 기본 라이브러리 및 JVM 구현은 기본 힙으로부터 메모리를 할당합니다. OutOfMemoryError는 기본 힙에서 할당이 실패할 경우 발생합니다. 예를 들어, 다음 오류 메시지는 스왑 공간이 부족함을 나타냅니다. 이 오류는 운영 체제의 구성 문제 또는 시스템의 다른 프로세스에 의해 발생할 수 있으며 많은 메모리를 소비합니다.

    java.lang.OutOfMemoryError: request <size> bytes for <reason>. 
    Out of swap space?
    
     

메모리 부족 문제는 구성(해당 응용 프로그램이 실제로 그렇게 많은 메모리를 필요로 함) 문제 또는 메모리 사용을 줄이기 위한 프로파일링 및 최적화를 필요로 하는 응용 프로그램의 성능 문제 때문일 수 있습니다. 메모리 사용을 줄이기 위한 메모리 설정 구성 및 응용 프로그램 프로파일링은 이 기사의 범위를 넘어서는 것이지만 관련 정보에 대해 핫스폿 VM 메모리 관리 백서(PDF)를 참조하거나 NetBeans IDE Profiler와 같은 프로파일링 도구를 사용할 수 있습니다.

메모리 누출

JVM은 자동 메모리 관리를 책임지고 있으며 이는 응용 프로그램에 사용되지 않은 메모리를 재생 이용합니다. 그러나 응용 프로그램이 더 이상 필요하지 않은 객체에 대한 참조를 유지하는 경우 객체는 가비지 컬렉션될 수 없으며 객체가 제거될 때까지 힙에서 공간을 차지합니다. 이러한 의도하지 않은 객체 유지를 메모리 누출이라고 합니다. 응용 프로그램이 많은 양의 메모리를 누출하면 결국에는 메모리를 다 사용하여 OutOfMemoryError가 발생합니다. 또한 가비지 컬렉션은 응용 프로그램이 여유 공간을 만들려고 함에 따라 더욱 더 빈번히 발생하므로 응용 프로그램의 실행 속도가 느려집니다.

종료자

OutOfMemoryError의 또 다른 가능한 원인은 종료자의 과도한 사용입니다. java.lang.Object 클래스에는 finalize라는 보호된 메소드가 있습니다. 클래스는 이 finalize메소드를 대체하여 해당 클래스의 객체가 가비지 컬렉션에 의해 재생 이용되기 전에 시스템 자원을 지우거나 정리를 수행할 수 있습니다. 객체에 대해 호출될 수 있는 finalize메소드는 해당 객체의 finalizer입니다. 종료자가 실행되는 시기 또는 적어도 실행은 될지 여부가 보장되지 않습니다. 종료자가 있는 객체는 종료자가 실행될 때까지 가비지 컬렉션되지 않습니다. 따라서 종료 대기 중인 객체는 응용 프로그램에 의해 더 이상 참조되지 않더라도 메모리를 유지하여 메모리 누출과 유사한 문제가 발생할 수 있습니다.

교착 상태

교착 상태는 둘 이상의 스레드가 각기 다른 스레드가 잠금을 해제하도록 기다릴 때 발생합니다. Java 프로그래밍 언어는 모니터를 사용하여 스레드를 동기화합니다. 각 객체는 모니터와 연관되어 있어 객체 모니터라고도 할 수 있습니다. 스레드가 객체에서 synchronized 메소드를 호출하는 경우 해당 객체는 잠깁니다. 동일한 객체에서synchronized 메소드를 호출하는 또 다른 스레드는 잠금이 해제될 때까지 차단됩니다. 내장 동기화 지원 외에도 J2SE 5.0에 도입된 java.util.concurrent.locks 패키지는 조건을 잠금고 기다리는 프레임워크를 제공합니다. 교착 상태는 java.util.concurrent 잠금뿐만 아니라 객체 모니터와도 연관될 수 있습니다.

일반적으로 교착 상태는 응용 프로그램 또는 응용 프로그램의 일부가 응답하지 않도록 만듭니다. 예를 들어, GUI(그래픽 사용자 인터페이스) 업데이트를 책임지고 있는 스레드가 교착 상태에 빠지면 GUI 응용 프로그램이 중단되고 어떠한 사용자 동작에도 응답하지 않습니다.

루핑 스레드

루핑 스레드는 또한 응용 프로그램이 중단되도록 만들 수 있습니다. 하나 이상의 스레드가 무한 루프에서 실행되고 있는 경우 해당 루프는 사용 가능한 모든 CPU 주기를 다 소비하고 응용 프로그램의 나머지 부분이 응답하지 않도록 만들 수 있습니다.

치열한 잠금 경합

동기화는 다중 스레드 응용 프로그램에 많이 사용되어 공유 자원에 대한 액세스를 상호 배제하고 다중 스레드 간의 작업을 조정 및 완료합니다. 예를 들어, 응용 프로그램이 객체 모니터를 사용하여 데이터 구조에서 업데이트를 동기화합니다. 두 스레드가 동시에 데이터 구조를 업데이트하려고 하면 한 스레드만이 객체 모니터를 획득하여 데이터 구조 업데이트를 진행할 수 있습니다. 한편, 다른 스레드는 첫 번째 스레드가 업데이트를 완료하고 객체 모니터를 해제할 때까지 synchronized 블록에 들어가기 위해 기다리므로 차단됩니다. 동기화 경합은 응용 프로그램 성능 및 확장성에 영향을 줍니다.

Java SE 6 플랫폼의 모니터링 및 관리 기능

Java SE 6의 모니터링 및 관리 지원에는 다양한 VM(가상 머신) 자원을 검사하기 위한 유용한 진단 도구와 프로그램 인터페이스가 포함되어 있습니다. 프로그램 인터페이스에 대한 자세한 내용은 API 사양을 참조하십시오.

JConsole은 Java 모니터링 및 관리 콘솔로서 이를 사용하여 런타임에 다양한 VM 자원 사용을 모니터링할 수 있습니다. 또한 응용 프로그램 실행 동안 이전 섹션에서 설명한 증상을 감시할 수 있습니다. JConsole을 사용하여 동일한 시스템에서 로컬로 실행되거나 다른 시스템에서 원격으로 실행되는 응용 프로그램에 연결하여 다음과 같은 정보를 모니터링할 수 있습니다.

  • 메모리 사용 및 가비지 컬렉션 작업
  • 스레드 상태, 스레드 스택 추적 및 잠금
  • 종료 대기 중인 객체의 수
  • 가동 시간 및 프로세스가 소비하는 CPU 시간과 같은 런타임 정보
  • JVM에 대한 입력 인수 및 응용 프로그램 클래스 경로와 같은 VM 정보

또한 Java SE 6에는 기타 명령줄 유틸리티가 포함되어 있습니다. jstat 명령은 메모리 사용, 가비지 컬렉션 시간, 클래스 로딩 및 JIT(Just-In-Time) 컴파일러를 비롯한 다양한 VM 통계를 인쇄합니다. jmap 명령를 사용하면 런타임에 힙 막대 그래프 및 힙 덤프를 얻을 수 있습니다. jhat 명령을 사용하면 힙 덤프를 분석할 수 있습니다. 또한 jstack 명령을 사용하면 스레드 스택을 추적할 수 있습니다. 이러한 진단 도구들은 특수 모드에서 시작할 필요 없이 모든 응용 프로그램에 연결할 수 있습니다.

JDK 도구를 사용한 진단

이 섹션에서는 JDK 도구를 사용하여 일반적인 Java SE 문제를 진단하는 방법에 대해 설명합니다. JDK 도구를 사용하면 응용 프로그램에 대한 보다 정확한 진단 정보를 얻을 수 있으며 응용 프로그램이 원래대로 작동하고 있는지 알 수 있습니다. 일부 경우에 진단 정보는 문제를 진단하고 근본 원인을 식별하기에 충분할 수 있습니다. 다른 경우에는 프로파일링 도구나 디버거를 사용하여 문제를 디버깅해야 할 수 있습니다.

각 도구에 대한 자세한 내용은 Java SE 6 도구 설명서를 참조하십시오.

메모리 누출 진단 방법

메모리 누출은 재현에 매우 긴 시간이 소요될 수 있으며 매우 드물거나 모호한 조건에서 발생하는 경우 특히 그렇습니다. 이상적인 경우는 개발자가 OutOfMemoryError가 발생하기 전에 메모리 누출을 진단하는 것입니다.

먼저 JConsole을 사용하여 메모리 누출이 계속해서 증가하는지 모니터링합니다. 이는 가능한 메모리 누출을 나타냅니다. 그림 1은 메모리 사용이 증가하고 있는 MemLeak라는 응용 프로그램에 연결된 JConsole의 메모리 탭을 보여줍니다. 메모리 탭 내에 삽입된 상자에서 GC(가비지 컬렉션) 작업을 관찰할 수 있습니다.

그림 1: 메모리 탭은 증가하는 메모리 사용을 보여주고 있으며 이는 가능한 메모리 누출을 나타냅니다.
그림 1: 메모리 탭은 증가하는 메모리 사용을 보여주고 있으며 이는 가능한 메모리 누출을 나타냅니다.

또는 다음과 같이 jstat 명령을 사용하여 메모리 사용 및 가비지 컬렉션 통계를 모니터링할 수 있습니다.

  $ <JDK>/bin/jstat -gcutil <pid> <interval> <count>

jstat -gcutil 옵션은 <count> 횟수 동안 지정된 표본 추출 <interval>의 각 표본에서 프로세스 ID <pid>의 실행 응용 프로그램의 힙 사용 및 가비지 컬렉션의 요약을 인쇄합니다. 이는 다음과 같은 표본 출력을 생성합니다.

  S0     S1     E      O      P     YGC   YGCT    FGC    FGCT     GCT
0.00 0.00 24.48 46.60 90.24 142 0.530 104 28.739 29.269
0.00 0.00 2.38 51.08 90.24 144 0.536 106 29.280 29.816
0.00 0.00 36.52 51.08 90.24 144 0.536 106 29.280 29.816
0.00 26.62 36.12 51.12 90.24 145 0.538 107 29.552 30.090

jstat 출력 및 다양한 VM 통계를 얻기 위한 기타 옵션에 대한 자세한 내용은 jstat 설명서 페이지를 참조하십시오.

힙 막대 그래프

응용 프로그램에 메모리 누출이 있는 것으로 의심되는 경우 jmap 명령을 사용하면 총 인스턴스 수 및 각 클래스의 인스턴스가 사용한 총 바이트 수를 비롯한 클래스당 통계를 보여주는 힙 막대 그래프를 얻을 수 있습니다. 다음 명령줄을 사용합니다.

$ <JDK>/bin/jmap -histo:live <pid>
 

힙 막대 그래프 출력은 다음과 유사합니다.

num   #instances    #bytes  class name
--------------------------------------
  1:    100000    41600000  [LMemLeak$LeakingClass;
  2:    100000     2400000  MemLeak$LeakingClass
  3:     12726     1337184  <constMethodKlass>
  4:     12726     1021872  <methodKlass>
  5:       694      915336  [Ljava.lang.Object;
  6:     19443      781536  <symbolKlass>
  7:      1177      591128  <constantPoolKlass>
  8:      1177      456152  <instanceKlassKlass>
  9:      1117      393744  <constantPoolCacheKlass>
 10:      1360      246632  [B
 11:      3799      238040  [C
 12:     10042      160672  MemLeak$FinalizableObject
 13:      1321      126816  java.lang.Class
 14:      1740       98832  [S
 15:      4004       96096  java.lang.String
 < more .....>
 

jmap -histo 옵션은 프로세스 ID <pid>의 실행 응용 프로그램의 힙 막대 그래프를 요청합니다. jmap이 힙의 라이브 객체만 카운트하도록 live 하위 옵션을 지정할 수 있습니다. 연결할 수 없는 객체를 비롯한 모든 객체를 카운트하려면 다음 명령줄을 사용합니다.

$ <JDK>/bin/jmap -histo <pid>
 

두 힙 막대 그래프(하나는 연결할 수 없는 객체를 비롯한 모든 객체를 카운트 하는 그래프, 다른 하나는 라이브 객체만 카운트하는 그래프)를 비교하여 어떤 객체가 가비지 컬렉션될 것인지 확인하는 것이 유용한 경우가 있을 수 있습니다. 하나 이상의 힙 막대 그래프 스냅샷에서 일반적으로 다음과 같은 특성을 지니는 메모리 누출이 있을 수 있는 클래스를 식별할 수 있습니다.

  • 인스턴스가 예상치 않게 많은 양의 메모리를 사용함
  • 클래스의 인스턴스 수가 시간이 지남에 따라 높은 속도로 증가함
  • 가비지 컬렉션될 것으로 예상한 클래스 인스턴스가 가비지 컬렉션되지 않음

jmap 유틸리티를 사용하여 얻은 이전의 힙 막대 그래프가 LeakingClass 및 그 배열이 가장 많은 인스턴스 수를 가지는 것으로 나타나 메모리 누출이 의심됩니다.

힙 막대 그래프는 일부 경우 메모리 누출을 진단하는 데 필요한 정보를 제공합니다. 예를 들어, 응용 프로그램이 소수의 몇 군데에서만 누출 클래스를 사용하는 경우 소스 코드에서 쉽게 누출을 찾을 수 있습니다. 반면에 java.lang.String 클래스와 같이 응용 프로그램에서 누출 클래스가 널리 사용되는 경우 객체에 대한 참조를 추적하고 힙 덤프를 분석하여 심도 있게 진단해야 합니다.

힙 덤프

다음 방법을 통해 힙 덤프를 얻을 수 있습니다. 첫 번째 방법은 다음 명령줄을 통해 jmap 명령을 사용하여 힙 덤프를 얻는 것입니다.

$ <JDK>/bin/jmap -dump:live,file=heap.dump.out,format=b <pid>
 

이는 다음과 같은 표본 출력을 생성합니다.

Dumping heap to d:\demo\heap.dump.out ...
Heap dump file created
 

jmap -dump 옵션은 프로세스 ID <pid>의 실행 응용 프로그램의 힙 덤프가 지정된 파일 이름 heap.dump.out에 작성되도록 요청합니다. -histo 옵션과 유사하게 live 하위 옵션은 선택 사항이며 라이브 객체만이 덤프되도록 지정합니다.

두 번째 방법은 그림 2에 나타난 것처럼 HotSpotDiagnostic MBean의 dumpHeap 연산을 호출하여 JConsole에서 힙 덤프를 얻는 것입니다.

그림 2: HotSpotDiagnostic MBean의 <code>dumpHeap</code> 연산을 호출하여 JConsole에서 힙 덤프를 얻습니다.
그림 2: HotSpotDiagnostic MBean의 dumpHeap 연산을 호출하여 JConsole에서 힙 덤프를 얻습니다.
 

이는 JConsole을 사용하여 응용 프로그램을 모니터링할 때 특히 유용하고 편리한데 그 이유는 하나의 도구를 사용하여 모니터링 및 문제 해결을 수행할 수 있기 때문입니다. 또한 JConsole을 사용하여 응용 프로그램에 원격으로 연결할 수 있으므로 또 다른 시스템에서 힙 덤프를 요청할 수 있습니다.

지금까지 런타임에 힙 덤프를 얻을 수 있는 두 가지 방법에 대해 살펴보았습니다. HeapDumpOnOutOfMemoryError HotSpot VM 옵션을 설정하여 OutOfMemoryError가 처음 발생할 때 힙 덤프를 작성하도록 요청할 수도 있습니다. 응용 프로그램을 시작할 때 명령줄에 이 옵션을 설정할 수 있습니다.

$ <JDK>/bin/java -XX:+HeapDumpOnOutOfMemoryError ... 
 

다음과 같이 jinfo 명령을 사용하여 응용 프로그램이 실행되고 있는 동안 이 옵션을 설정할 수도 있습니다.

$ <JDK>/bin/jinfo -flag +HeapDumpOnOutMemoryError <pid>
 

마지막으로, 그림 3에 나타난 것처럼 HotSpotDiagnostic MBean의 setVMOption 연산을 호출하여 JConsole에서 HeapDumpOnOutOfMemoryError 옵션을 설정할 수 있습니다.

그림 3: HotSpotDiagnostic MBean의 <code>setVMOption</code> 연산을 호출하여 VM 옵션을 설정합니다.
그림 3: HotSpotDiagnostic MBean의 setVMOption 연산을 호출하여 VM 옵션을 설정합니다.
 

OutOfMemoryError가 발생하면 java_pid<pid>.hprof라는 이름의 힙 덤프 파일이 자동으로 작성됩니다.

java.lang.OutOfMemoryError: Java heap space
Dump heap to java_pid1412.hprof ...
Heap dump file created [68354173 bytes in 4.416 secs ]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at MemLeak.consumeMemory(MemLeak.java:25)
at MemLeak.main(MemLeak.java:6)
 

힙 분석

힙 덤프 파일이 작성되면 jhat 명령을 사용하여 힙 분석을 수행하고 어떤 참조가 누출이 의심되는 객체를 활성 상태로 유지하는지 확인할 수 있습니다.

$ <JDK>/bin/jhat heap.dump.out
 

이는 다음과 같은 표본 출력을 생성합니다.

Reading from heap.dump.out...
Dump file created Tue Jul 20 12:05:59 PDT 2006
Snapshot read, resolving...
Resolving 283482 objects...
Chasing references, expect 32 dots..........................................
Eliminating duplicate references............................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
 

jhat 유틸리티(이전의 HAT 힙 분석 도구)는 힙 덤프를 읽고 지정된 포트에서 HTTP 서버를 시작합니다. 그런 다음 브라우저를 사용하여 서버에 연결하고 지정된 힙 덤프에 대해 쿼리를 실행합니다. 그림 4는 jhat가 분석하는 힙 덤프의 모든 클래스(java.* 및 javax.* 제외)를 보여줍니다. 이 도구는 다음을 비롯한 여러 쿼리를 지원합니다.

  • 주어진 객체에 설정된 루트의 모든 참조 경로 표시. 이 쿼리는 메모리 누출을 찾는데 특히 유용합니다.
  • 모든 클래스에 대한 인스턴스 카운트 표시
  • 모든 클래스에 대한 인스턴스 카운트 및 크기를 비롯한 힙 막대 그래프 표시
  • 종료자 요약 표시
그림 4: 힙 덤프는 <code>java.*</code> 및 <code>javax.*</code>를 제외한 모든 클래스를 보여줍니다.
그림 4: 힙 덤프는 java.* 및 javax.*를 제외한 모든 클래스를 보여줍니다.
 

내장 OQL(Object Query Language) 인터페이스를 통해 사용자 정의 쿼리를 개발하여 특정 문제를 드릴 다운할 수도 있습니다. 예를 들어, 문자열 길이가 100 이상인 모든java.lang.String 객체를 찾으려면 OQL query 페이지에서 다음 쿼리를 입력합니다.

select s from java.lang.String s where s.count >= 100
 

과도한 종료자 사용 진단 방법

과도한 종료자 사용은 메모리를 유지하고 응용 프로그램이 해당 메모리를 신속하게 재생 이용하는 것을 방해합니다. 이러한 과도한 사용은 OutOfMemoryError를 유발할 수 있습니다. 그림 5가 나타낸 것처럼 JConsole을 사용하여 종료 대기 중인 객체 수를 모니터링할 수 있습니다.

그림 5: JConsole의 VM 탭은 종료 대기 중인 객체 수를 보여줍니다.
그림 5: JConsole의 VM 탭은 종료 대기 중인 객체 수를 보여줍니다.
 

앞에서 설명한 것처럼 jhat를 사용하여 힙 덤프에 어떤 종료 가능한 객체가 있는지도 확인할 수 있습니다.

또한 Solaris 및 Linux 운영 체제에서 jmap 유틸리티를 사용하여 종료 가능한 객체의 클래스를 확인할 수 있습니다.

$ <JDK>/bin/jmap -finalizerinfo <pid>
 

교착 상태 진단 방법

Java SE 6은 응용 프로그램에 교착 상태가 발생했는지 확인할 수 있는 매우 편리한 두 가지 방법을 제공하며 java.util.concurrent 잠금을 지원하도록 교착 상태 감지 기능이 향상되었습니다. JConsole 및 jstack 명령은 객체 모니터에 관련된 교착 상태 즉, synchronized 키워드 또는 java.util.concurrent 소유 가능한 동기화를 사용하여 얻은 잠금을 찾을 수 있습니다.

그림 6은 Deadlock 응용 프로그램에 2개의 교착 상태가 있음을 보여주고, Deadlock 2 탭은 객체 모니터에 차단된 3개의 교착 상태 스레드를 보여줍니다. 각 교착 상태 탭은 교착 상태에 관련된 스레드 목록을 보여주고 스레드가 차단된 잠금을 식별하며 해당 잠금을 소유한 스레드를 가리킵니다.

그림 6: JConsole이 2개의 교착 상태를 감지하고 세부 내용을 제공합니다.
그림 6: JConsole이 2개의 교착 상태를 감지하고 세부 내용을 제공합니다.
 

jstack 유틸리티를 사용하여 스레드 덤프를 얻고 교착 상태를 감지할 수도 있습니다.

$ <JDK>/bin/jstack <pid>
 

다음은 java.util.concurrent 소유 가능한 동기화에 관련된 교착 상태 1개를 감지하는 표본 jstack 출력의 아래 부분입니다.

Sample jstack output
더 큰 표본을 보려면 여기를 누르십시오.

루핑 스레드 진단 방법

CPU 사용 증가는 루핑 스레드의 징조 중 하나입니다. JTop은 응용 프로그램의 스레드당 CPU 사용 시간을 보여주는 JDK 데모입니다. JTop은 CPU 사용량별로 스레드를 정렬하여 CPU 시간을 과도하게 사용하고 있는 스레드를 쉽게 감지할 수 있게 해줍니다. 높은 스레드 CPU 소비가 예상된 동작이 아닌 경우 해당 스레드는 루핑일 수 있습니다.

JTop을 독립 실행형 GUI로 실행할 수 있습니다.

$ <JDK>/bin/java -jar <JDK>/demo/management/JTop/JTop.jar
 

또는 JConsole 플러그인으로 실행할 수 있습니다.

$ <JDK>/bin/jconsole -pluginpath <JDK>/demo/management/JTop/JTop.jar 
 

그림 7에 나타난 것처럼 응용 프로그램의 각 스레드가 사용하고 있는 CPU 시간을 보여주는 추가 JTop 탭을 통해 JConsole 도구를 시작합니다. JTop 탭은 LoopingThread가 많은 양의 CPU 시간을 사용하고 있고 사용량이 점점 증가하고 있음을 보여주며 따라서 루핑 스레드가 의심됩니다. 개발자는 이 스레드의 소스 코드를 검토하여 무한 루프가 포함되어 있는지 확인해야 합니다.

그림 7: JTop 탭은 응용 프로그램의 각 스레드가 얼마의 CPU 시간을 사용하는지 보여줍니다.
그림 7: JTop 탭은 응용 프로그램의 각 스레드가 얼마의 CPU 시간을 사용하는지 보여줍니다.

치열한 잠금 경합 진단 방법

어떤 잠금이 병목 현상인지 판단하는 것은 꽤 어려울 수 있습니다. JDK는 잠금 경합에 소비된 총 누적 시간뿐만 아니라 스레드가 객체 모니터에서 차단되거나 대기한 횟수와 같은 스레드당 경합 통계를 제공합니다. 그림 8에 나타난 것처럼 스레드가 객체 모니터에서 차단되거나 대기한 횟수에 대한 정보는 JConsole의 스레드 탭에 표시된 스레드 정보에서 항상 확인할 수 있습니다.

그림 8: 스레드 탭은 스레드가 객체 모니터에서 차단되거나 대기한 횟수를 보여줍니다.
그림 8: 스레드 탭은 스레드가 객체 모니터에서 차단되거나 대기한 횟수를 보여줍니다.
 

그러나 경합에 소비된 총 누적 시간을 추적하는 기능은 기본적으로 비활성화되어 있습니다. 그림 9에 나타나 것처럼 Threading MBean의ThreadContentionMonitoringEnabled 속성을 true로 설정하여 스레드 경합 시간의 모니터링을 활성화할 수 있습니다.

그림 9: Threading MBean의 <code>ThreadContentionMonitoringEnabled</code> 속성을 설정하여 스레드 경합의 모니터링을 활성화합니다.
그림 9: Threading MBean의 ThreadContentionMonitoringEnabled 속성을 설정하여 스레드 경합의 모니터링을 활성화합니다.
 

스레드 경합 통계를 확인하여 스레드에서 기대보다 치열한 잠금 경합이 발생했는지 판단할 수 있습니다. 그림 10에 나타난 것처럼 스레드 ID를 입력 인수로 사용하여 Threading MBean의 getThreadInfo 연산을 호출하여 스레드가 차단된 총 누적 시간을 얻을 수 있습니다.

그림 10: Threading MBean의 <code>getThreadInfo</code> 연산의 반환값입니다.
그림 10: Threading MBean의 getThreadInfo 연산의 반환값입니다.
 
요약

Java SE 6 플랫폼은 프로덕션 및 개발 환경에서 Java SE 응용 프로그램의 일반적인 문제를 진단할 수 있는 몇 가지 모니터링 및 관리 도구를 제공합니다. JConsole을 사용하면 응용 프로그램을 관찰하여 증상을 확인할 수 있습니다. 또한 JDK 6에는 몇 가지 기타 명령줄 도구도 포함되어 있습니다. jstat 명령은 메모리 사용 및 가비지 컬렉션 시간과 같은 다양한 VM 통계를 인쇄합니다. jmap 명령을 사용하면 런타임에 힙 막대 그래프 및 힙 덤프를 얻을 수 있습니다. jhat 명령을 사용하면 힙 덤프를 분석할 수 있습니다. 또한jstack 명령을 사용하면 스레드 스택을 추적할 수 있습니다. 이러한 진단 도구들은 특수 모드에서 시작할 필요 없이 모든 응용 프로그램에 연결할 수 있습니다. 이러한 도구들을 사용하여 응용 프로그램의 문제를 보다 효율적으로 진단할 수 있습니다.

추가 정보
저자 정보

Mandy Chung은 Sun Microsystems의 Java SE 모니터링 및 관리 팀장이며, java.lang.management API, 즉시 사용할 수 있는 원격 관리, JConsole 및기타 HotSpot VM 서비스가용성 기술을 개발하고 있습니다. 저자의 블로그를 방문하십시오.


* "Java Virtual Machine" 및 "JVM"이라는 용어는 Java 플랫폼용 가상 머신을 의미합니다.

 Java SE 6 빌드 95 이하 버전을 사용하는 경우 dumpHeap 연산은 첫 번째 인수만을 사용하며 라이브 객체만을 덤프합니다.

Posted by 1010
반응형

이클립스에서 SVN을 이용해서 버전관리를 할때, 버전관리가 필요없는 파일을 Commit 하거나 Update 해서 오동작하는 경험을 해봤을 것이다. 이럴 경우, 아예 버전관리대상에서 제외함으로써 문제가 될 소지를 없앨 수 있다.

1. Window > Preference > Team > Ignored Resources

     버전관리 대상에서 제외시킬 파일의 패턴을 정의해 둠으로써 관리가 가능하다.

2. 동기화를 진행 > 제외하고자 하는 파일 또는 디렉토리 위에서 마우스 오른쪽 버튼 > Team > Add to svn:ignore

     해당 파일이나 디렉토리에 대해서 ignore을 설정할 수 있다.

Posted by 1010
55.jrebel2012. 5. 2. 17:51
반응형

출처 : http://blog.naver.com/lkssky2002/120140342334



좋은 플러그인 정보를 얻었다.

 

Jrebel.

일반적으로 개발시 html, jsp 등 뷰단은 서버 재부팅 없이 바로 수정내용을 확인할 수 있지만,

java 클래스 파일 변경시 꼭 was 가 재부팅되어야 수정내용이 적용된다.

 

하지만 Jreble 플러그인을 사용하면 java 클래스 파일 내용이 수정되어도 was 재부팅 없이 바로 확인가능할 수 있다.

톰캣을 사용하면 서버재부팅하는데 오랜 시간이 소요되지 않지만 웹로직이나

제우스등을 사용하여 테스트할때는 매번 서버 재부팅하는것이 바쁜 개발시간을 더 늘어지게 만들었는데 이 플러그인으로 개발시간을 조금이나마 단축하고 편하게 개발을 할수 있는 플러그인인것 같다.

 

원래는 유료이지만 이번에 트위터나 페이스북중 하나의 계정으로 해당 정보를 연결하면 무료로 사용할수 있어서 그걸로 이용ㅋ

 

순서 캡쳐같은것은 배재하고 간단한 순서만 명시해서 담번에도 설치하는데 참고해야겠다.

 

- 플러그인사이트 접속 : http://sales.zeroturnaround.com/

- 중앙부분의 Go to JRebel Social 클릭

- SNS 선택(페이스북으로 ㄱㄱ)

- 해당 어플리케이션 허가

- 정보 입력후 Register

- 이클립스 플러그인 설치 -> help -> eclipse marketplace

- JRebel for Eclipse -> Install

- 라이센스 관련 해서 accept 체크 후 finish -> 이클립스 재시작

- JRebel Configuration Wizard 창 -> License 탭 클릭

- 아래 Copy and paste your license code into the box below 하단 textarea에 아까 소셜 연결후 연결된 사이트에 명시된 Step3. Active Your License 부분의 내용을 복사하여 붙여넣기

- finish 탭 클릭하고 창닫기

- 이클립스 servers 탭에서 생성된 톰캣 서버 더블클릭

- publishing 클릭

- never publish automatically 체크

- JRebel인테그레이션 둘다 체크

- 저장

- 진행중인 프로젝트명에서 우클릭

- JRebel메뉴에서 두번째거(Generate rebel.xml in src/main/resources)  선택

- project/src/main/resources 에 rebel.xml파일 생성 확인

- 테스트 해서 바로 적용되면 끝.

 

 

바쁜데 서버 내렸다 올렸다 확인할려면 시간 낭비가 클텐데 도움 될듯한 플러그인 인것 같다.

Posted by 1010
55.jrebel2012. 5. 2. 17:47
반응형

1. 참조 링크

    http://www.zeroturnaround.com/
    https://social.jrebel.com/
    http://blog.naver.com/lkssky2002/120140342334




2. 설치

   - 이클립스 Software Update 를 사용한다. (http://www.zeroturnaround.com/update-site)
     jrebel 하위의 모든 패키지를 설치하는 것이 아님에 주의하자 (사이트 참조)

   - social 버전(비상업용 개발)의 경우 무료로 제한 없이 사용할 수 있다.
      이 경우에는 여기 로 먼저 진입하여 페이스북/트위터 계정을 사용하여 라이센스 코드를 발급받자.




3. 설치과정 및 이후 설정은 다음 링크를 참고한다.

    http://www.zeroturnaround.com/jrebel/eclipse-jrebel-tutorial

    - 더불어 WAS의 reloadable 옵션을 false 로 해야하는지 아닌지 모르겠지만 왠지 false로 해야 할 것 같다. (-_  -;)




4. 설치가 완료되었으면 확인한다.
    
    - 클래스를 수정하고 다시 그 클래스를 사용하는 페이지를 호출했을 때 서버 재기동 없이
      로그에 JRebel: Reloading class '클래스명' 이 나오면 성공!



출처 : http://happybruce.tistory.com/916

Posted by 1010
56. Eclipse Etc...2012. 5. 2. 17:35
반응형

사람을 위한 자동화: Eclipse 플러그인으로 코드 품질 높이기

다섯 개의 유용한 플러그인으로 Eclipse 내에서 코드 품질 분석 자동화 하기

Paul Duvall, CTO, Stelligent Incorporated

요약:  코드를 빌드하기 전에 코드에서 중대한 문제를 발견할 수 있다면 어떨까요? 재미있게도, 소프트웨어에 문제가 드러나기 전에 문제를 발견할 수 있도록 해주는 JDepend와 CheckStyle 같은 Eclipse 플러그인이 있습니다. 사람을 위한 자동화 시리즈에서는, 자동화 전문가 Paul Duvall이 Eclipse에서 정적인 분석 플러그인을 설치, 구성, 사용하는 방법을 예제를 통해 설명합니다. 이제 여러분도 개발 사이클에서 문제를 조기에 방지할 수 있습니다.

이 연재 자세히 보기

이 기사에 태그:  애플리케이션_개발이클립스

원문 게재일:  2007 년 4 월 24 일 
난이도:  초급 
페이지뷰:  9932 회 
의견:   0 (보기 | 의견 추가 - 로그인)

평균 평가 등급 4 개 총 31표 평균 평가 등급 (31 투표수)
아티클 순위

시리즈 소개

개발자로서, 사용자를 위해 프로세스를 자동화 하고 있습니다. 하지만, 정작 우리들 자신의 개발 프로세스를 자동화 할 수 있는 기회를 간과하고 있습니다. 따라서, 사람을 위한 자동화 시리즈에서는 소프트웨어 개발 프로세스를 자동화 하는 방법을 연구하고, 자동화를 적용할 시기와 방법을 설명합니다.

소프트웨어를 개발할 때, 필자가 기본적으로 강조하는 부분은 결함이 코드 베이스에 들어가지 않도록 하는 것 또는 이것의 수명을 제한하는 것이다. 다시 말해서, 가능하면 빨리 결함을 찾으려고 노력한다. 더 나은 코드를 작성하는 방법을 배우고, 소프트웨어를 효과적으로 테스트 하는 방법을 배워갈수록, 결함을 더욱 잘 찾아내게 된다. 하지만, 중대한 결함을 찾을 수 있는 보안 망(safety net)도 갖고 싶기는 하다.

본 시리즈의 8월 기사에서, 감시 툴을 빌드 프로세스에 통합하면(Ant 또는 Maven을 사용함) 잠재적 결함들을 찾는데 효과적이라는 결론을 내렸다. 비록, 이러한 방식이 일관성을 유지하고 IDE를 능가하는 부분도 있지만, 약간 보수적(reactionary)이기도 하다. 여러분은 소프트웨어를 로컬에서 구현하거나, Continuous Integration 빌드가 실행되기를 기다려야 한다. 하지만, Eclipse 플러그인을 사용하면, Continuous Integration을 통해 빌드 또는 통합하기 전에 위반 사항들을 발견할 수 있다. 바로 이것을 진보적인 프로그래밍(progressive programming)이라고 할 수 있으며, 코딩 하면서 품질 체크도 실행할 수 있다.

이 글에서는 "5대" 코드 분석 영역에 대해 설명하겠다.

  • 코딩 표준
  • 코드 중복
  • 코드 커버리지
  • 의존성 분석
  • 복잡성 모니터링

이러한 분석 영역들은 다음과 같은 Eclipse 플러그인을 사용한다.

  • CheckStyle: 코딩 표준
  • PMD의 CPD: 코드 중복 발견
  • Coverlipse: 코드 커버리지 측정
  • JDepend: 의존성 분석 제공
  • Eclipse Metrics 플러그인: 복잡성 탐지

Eclipse는 빌드 시스템이 아닙니다.

Eclipse 플러그인을 사용한다고 해서 빌드 프로세스의 일부로 이러한 감시 툴을 사용하지 못하게 하는 것은 말도 안 된다. 사실, Eclipse 플러그인을 사용하는데 따르는 규칙들은 빌드 프로세스에도 똑같이 적용되는 규칙들이다.

Eclipse 플러그인 설치하기

Eclipse 플러그인 설치는 매우 간단하며, 단지 몇 단계만 거치면 된다. 시작하기 전에, 플러그인의 다운로드 사이트의 URL을 파악하는 것이 좋다. 표 1에서 필자가 이 글에서 사용하는 플러그인 리스트를 정리했다.


표 1. 코드 향상 플러그인과 설치 URL 리스트 
목적Eclipse 플러그인 URL
CheckStyle코딩 표준 분석http://eclipse-cs.sourceforge.net/update/
Coverlipse코드 커버리지 테스트http://coverlipse.sf.net/update
CPDCopy/Paste 탐지http://pmd.sourceforge.net/eclipse/
JDepend패키지 의존성 분석http://andrei.gmxhome.de/eclipse/
MetricsComplexity monitoringhttp://metrics.sourceforge.net/update

이제 여러분은 유용한 플러그인을 어디서 구하는지 알았으니, 설치는 간단하다. Eclipse를 시작하고 다음 단계들을 수행한다.

  1. Help | Software Updates | Find and Install을 선택한다. (그림 1)



    그림 1. Eclipse 플러그인 찾기 및 설치
    Eclipse 플러그인 찾기 및 설치 



  2. Search for new features to install 라디오 버튼을 선택하고 Next를 클릭한다. 

  3. New Remote Site를 클릭하고, 원하는 플러그인의 이름과 URL을 입력한다. (그림 2) OK를 클릭한 다음 Finish를 클릭하면 Eclipse Update Manager가 디스플레이 된다. 



    그림 2. 새로운 원격 사이트 구성하기
    새로운 원격 사이트 구성하기 



  4. Eclipse Update Manager에서, 플러그인의 다양한 측면을 볼 수 있는 옵션이 있다. 일반적으로 위에 있는 것을 선택한다. (그림 3) 선택을 하고 Finish를 클릭한다. Eclipse는 이때 플러그인을 설치한다. Eclipse 인스턴스를 재시작 해야 한다.



    그림 3. Eclipse 플러그인 설치하기 
    Eclipse 플러그인 설치하기 

이 단계를 수행하면 Eclipse 플러그인이 설치된다. 플러그인의 이름과 관련 다운로드 위치를 변경하라.

CheckStyle로 표준 수정하기

코드 베이스에 대한 관리능력은 소프트웨어의 총 비용에 직접적인 영향을 미친다. 더욱이, 관리능력은 개발자의 욕구 불만에도 기여한다. 코드 변경이 쉬울수록, 새로운 제품 기능을 추가하기도 쉽다. CheckStyle 같은 툴은 큰 클래스, 긴 메소드, 사용되지 않는 변수 등에 대한 관리능력에 영향을 미치는 코딩 표준의 위반 사항들을 찾는데 도움이 된다.

PMD에 대해서

PMD라고 하는 오픈 소스 툴은 CheckStyle과 비슷한 기능을 제공한다. 나는 CheckStyle을 선호하지만, PMD도 강력하고 전문적이기 때문에, 여러분도 한번 사용해 보길 권한다.

Eclipse용 CheckStyle 플러그인을 사용하면 코딩 하면서 소스 코드 내에서 다양한 위반 사항에 대해 알 수 있고, 개발자들이 체크인 전에 위반 사항을 고치게 된다. CheckStyle 플러그인을 지속적인 코드 리뷰에 사용하는 것으로 생각하면 된다.

CheckStyle 플러그인을 설치하고, 다음과 같이 구성한다. (그림 4)

  1. Eclipse 메뉴에서 Project를 선택한 다음 Properties 아이템을 선택한다.

  2. CheckStyle active for this project 체크 박스를 선택하고 OK를 클릭한다. 



    그림 4. Eclipse에서 CheckStyle 플러그인 구성하기
    Eclipse에서 CheckStyle 플러그인 구성하기 

Eclipse는 워크스페이스를 재구현 하고 Eclipse 콘솔 안에 코딩 위반 사항들을 발견해 낸다. (그림 5)


그림 5. Eclipse내에 나타난 CheckStyle 위반 사항 리스트 
Eclipse내에 나타난 CheckStyle 위반 사항 리스트  

CheckStyle 플러그인을 사용하여 Eclipse 내에 코딩 표준 검사를 포함시키면, 코딩 하는 동안 코드를 향상시킬 수 있고, 개발 사이클에서 조기에 소스 코드의 잠재적 결함을 발견할 수 있다. 여러분의 시간, 좌절감, 나아가서 프로젝트 비용까지 줄일 수 있다는 이점도 있다.

Coverlipse로 커버리지 확인하기

Coverlipse는 상응하는 테스트를 갖고 있는 소스 코드의 비율을 평가하는데 사용할 수 있는 Eclipse 플러그인이다. Coverlipse를 사용하여 코드를 작성하는 동안 코드 커버리지를 평가할 수 있다. 벌써 패턴을 인식하고 있나?

Coverlipse 플러그인을 설치하고 Run Eclipse 메뉴 아이템을 선택하여 JUnit과 연결시킨다. 이렇게 하면 JUnit, SWT 애플리케이션, 자바™ 애플리케이션 같은 실행 구성들이 나타난다. 오른쪽 클릭하여 JUnit w/Coverlipse 노드에서 New를 선택한다. 여기서부터, JUnit 테스트의 위치를 규명해야 한다. (그림 6)


그림 6. Coverlipse를 구성하여 코드 커버리지 확보하기 
Coverlipse를 구성하여 코드 커버리지 확보하기  

Run을 클릭하면, Eclipse는 Coverlipse를 실행하고 소스 코드에 마커를 삽입한다. (그림 7) 이것은 JUnit 테스트로 연결되었던 코드의 부분들을 나타낸다.


그림 7. Coverlipse에 의해서 생성된 리포트와 삽입된 클래스 마커
Coverlipse에 의해서 생성된 리포트와 삽입된 클래스 마커 

보다시피, Coverlipse Eclipse 플러그인을 사용하여 훨씬 더 빠르게 코드 커버리지를 결정할 수 있다. 이 기능은 코드를 CM 시스템에 체크인 하기 전에 테스팅 하는데 도움이 된다. 이 얼마나 진보적인 프로그래밍인가?

CPD로 코드 중복 발견하기

PMD 플러그인은 CPD(Copy Paste Detector)라고 하는 기능을 제공하는데, 이것은 중복된 코드를 찾아낸다. Eclipse에서 이 툴을 사용하려면, CPD 유틸리티가 포함된 PMD용 Eclipse 플러그인을 설치해야 한다.

중복 코드를 찾아내려면, Eclipse 프로젝트를 오른쪽 클릭하고, PMD | Find Suspect Cut and Paste를 선택한다. (그림 8)


그림 8. CPD 플러그인을 사용하여 Copy and Paste 체크 실행하기 
CPD 플러그인을 사용하여 Copy and Paste 체크 실행하기  

CPD를 실행했다면, report 폴더가 Eclipse 루트 디렉토리에 생성되고, 여기에는 cpd.txt라는 파일이 포함된다. 이곳에 모든 중복 코드들이 나열된다. cpd.txt 파일 예제는 그림 9를 참조하라.


그림 9. Eclipse 플러그인에서 생성된 CPD 텍스트 파일 
Eclipse 플러그인에서 생성된 CPD 텍스트 파일  

중복 코드를 직접 찾기란 어려운 일이지만, CPD 같은 툴을 사용하면 코딩 하는 동안 중복 코드를 빠르게 찾아낼 수 있다.

JDepend를 이용한 의존성 검사

JDepend는 무료로 사용할 수 있는 오픈 소스 툴로서, 패키지 의존성에 대한 객체 지향식의 측정법을 제공한다. 코드 베이스의 복원력에 대한 지표라고 할 수 있다. 다시 말해서, JDepend는 아키텍처의 정합성을 측정하는데 사용된다.

Eclipse 플러그인 외에도, JDepend는 Ant 태스크, Maven 플러그인, 자바 애플리케이션을 사용하여 측정 결과를 얻는다. 각각은 같은 정보를 다르게 전달한다. 하지만, Eclipse 플러그인이 가진 중요한 차이점 및 효과라고 한다면 정보를 (여러분이 코딩한 대로) 소스 코드에 매우 근접하게 제공한다는 점이다.

그림 10은 소스 폴더를 오른쪽 클릭하고, Run JDepend Analysis를 선택하여 JDepend용 Eclipse 플러그인을 사용하는 방법을 보여준다. 소스 코드를 갖고 있는 폴더를 선택하라. 그렇게 하지 않으면, 메뉴 옵션을 볼 수 없다.


그림 10. JDepend Analysis를 사용하여 코드 분석하기
JDepend Analysis를 사용하여 코드 분석하기 

JDepend 분석을 실행할 때 생성되는 리포트는 그림 11에 나와있다. 왼쪽 패인은 패키지를 나타내고, 오른쪽 패인은 각 패키지의 의존성을 나타낸다.


그림 11. Eclipse 내 프로젝트의 패키지 의존성 
Eclipse 내 프로젝트의 패키지 의존성  

JDepend 플러그인은 이 아키텍처가 시간이 흘러도 유지될 수 있는지의 여부를 볼 수 있는 많은 정보를 제공하고 있다. 가장 중요한 것은 코딩 하는 동안 데이터를 볼 수 있다는 점이다.

Metrics로 복잡성 평가하기

"5대" 코드 분석 영역의 마지막 영역은 복잡성이다. Eclipse는 Metrics라고 하는 플러그인을 제공한다. 이것은 복잡성을 포함하여 유용한 코드 메트릭스를 제공하는데, 이것은 메소드의 고유 경로의 수를 측정한 것이다.

Metrics 플러그인을 설치하고 Eclipse를 재시작 한다. 다음 단계들을 수행한다.

  1. 프로젝트를 오른쪽 클릭하고, Properties 메뉴를 선택한다. 결과 윈도우에서, Enable Metrics plugin 체크 박스를 선택하고OK를 클릭한다. (그림 12)



    그림 12. Metrics 구성하기 
    Metrics 구성하기  



  2. Eclipse에서 Window 메뉴를 선택하여 Metrics 뷰를 열고 Show View | Other...를 선택한다.

  3. Metrics | Metrics View를 선택하여 윈도우를 연다. (그림 13) 자바 퍼스펙티브를 사용하고 프로젝트를 재구현 하여 메트릭스를 디스플레이 한다.



    그림 13. Eclipse에서 Metrics View 열기 
    Eclipse에서 Metrics View 열기  



  4. OK를 클릭하면 그림 14에 나온 것 같은 윈도우가 디스플레이 된다. 

    이 경우, 나는 개별 메소드의 복잡성을 보고 있다. 정말로 좋은 점은 Metrics 리스트에서 메소드를 더블 클릭할 수 있고, 플러그인이 Eclipse 에디터에서 그 메소드용 소스 코드를 연다는 점이다. 정정하기가 아주 쉬워졌다.



    그림 14. 메소드용 Cyclomatic Complexity 보기
    메소드용 Cyclomatic Complexity 보기 

앞서 언급했지만, Eclipse Metrics는 소프트웨어를 개발하는 동안 코드를 향상시킬 수 있는 강력한 메트릭스를 제공한다.

직접 사용해 보기

이 글에서 언급한, 코딩 표준, 코드 중복, 코드 커버리지, 의존성 분석, 복잡성 모니터링 등 "5대" 코드 품질 평가를 하는 것이 중요하다고 생각한다. 개발 사이클에서 조기에 코드의 품질을 향상시킬 수 있는 PMD와 FindBugs 같은 기타 Eclipse 플러그인들도 많이 있다는 것도 알아두기 바란다. 원하는 툴이나 선호하는 평가 방식과 별도로, 코드를 적극적으로 향상시키려는 노력을 기울여야 하며, 수동의 코드 리뷰 프로세스도 더욱 효율성 있게 해야 한다. 이 툴을 사용해 보면, 그 동안 이 툴 없이 어떻게 살았는지에 대한 의문이 일 것이다.

기사의 원문보기


참고자료

교육

제품 및 기술 얻기

토론

필자소개

Paul Duvall

Paul Duvall은 Stelligent Incorporated의 CTO이다.UML™ 2 Toolkit Toolkit을 공동 집필했으며 곧 출간될 Addison-Wesley Signature Series, Continuous Integration: Improving Software Quality and Reducing Risk의 공동 저자이다.

Posted by 1010
02.Oracle/DataBase2012. 5. 2. 16:12
반응형


  • 역주는 항상 이러한 스타일로 표시하겠습니다. 또한, 편집자가 문서 내에 남겨둔 주석(<!-- -->내부를 말합니다) 중 읽어둘만 하다 생각되는 것을 이런 스타일로 표시했습니다. 원문과 혼동 없으시길 바랍니다.
  • 원본에서 사용하는 마크업 구조를 번역에 사용할 시간은 내기 어렵고, 번역자의 오류가 있다면 빨리 발견할 수 있어야 하므로 이 번역에서는 영문 원본과 한글을 함께 유지합니다. 영문을 숨기길 원한다면, 상단 회색 음영에 마우스를 올리면 나타나는 메뉴에서 "영문 숨김"을 사용하실 수 있습니다. 하지만 링크를 사용할 수 없게 되므로 권장하는 방법은 아닙니다.
  • introduction 에서 설명되겠지만, 이 명세는 몇가지 이유로 인해 여태까지의 명세와는 전혀 다른 수준의 상세함을 갖고 있습니다. 이러한 상세함의 상당수는 브라우저 제작자를 위해 의도된 내용으로서, 이 번역본의 주된 독자층에게는 꼭 필요한 내용은 아닐 수 있습니다. 따라서 번역에서는 이러한 상세한 내용 중 상당부분을 건너뛸 것입니다. 이렇게 건너뛰어진 내용은 이와 같이, 또는 브라우저 제작자 대상 내용입니다.와 같이 나타날 것이며, 내용은 온존되어 있지만 숨겨져 있습니다. 전자의 경우는 마우스오버로, 후자의 경우는 클릭으로 숨겨진 내용을 확인해 보실 수 있습니다.
  • 그러나 명세 내부의 하이퍼링크를 클릭하여 이동한 경우에는 모든 내용이 숨김 없이 드러나게 되어 있습니다.
  • 명세의 번역을 진행한 그룹에서 몇가지 예제를 제작하여 브라우저 호환성 등을 테스트해본 것이 있습니다. 클리어보스 데모 와 같이 나타날 것입니다. 이러한 예제들은 공식적으로 문서화 된 것이 아닌, 스터디 그룹의 주관적인 내용을 포함하므로 혼동 없으시길 바랍니다.

초록

이 명세는 월드 와이드 웹의 코어 언어 : 하이퍼텍스트 마크업 랭귀지(HTML) 의 5번째 주요 개정판을 정의합니다. 이 버전에서는 웹 프로그래머를 위한 새로운 기능들, 기존의 웹 저작 경향을 분석한 결과에 기초한 새로운 요소들, 그리고 상호작용성을 개선하기 위해 사용자 에이전트들이 준수해야 할 사항들을 명확하게 제시하고 있습니다.

This specification defines the 5th major revision of the core language of the World Wide Web: the Hypertext Markup Language (HTML). In this version, new features are introduced to help Web application authors, new elements are introduced based on research into prevailing authoring practices, and special attention has been given to defining clear conformance criteria for user agents in an effort to improve interoperability.

이 문서의 상태

이 섹션은 명세가 발간된 시점에서의 문서의 상태를 설명합니다. 다른 문서들이 이 문서보다 우선할 수 있습니다. 현재의 W3C 발행본들과 최근의 발행본들에 대한 리스트는 http://www.w3.org/TR/, W3C 기술문서 목록에서 확인하실 수 있습니다.

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the most recently formally published revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

W3C에서 관리하도록 이 문서에 관한 코멘트를 남기길 원한다면 공개된 버그 데이터베이스를 통해 주시기 바랍니다. 계정을 가지고 있지 않다면 다음 폼을 이용할 수 있습니다.

If you wish to make comments regarding this document in a manner that is tracked by the W3C, please submit them via using our public bug database. If you do not have an account then you can enter feedback using this form:

Feedback Comments

피드백을 입력하실 때는 해당 섹션의 제목을 주의깊게 입력하고, 잘못된 텍스트를 따옴표로 감싸 주십시오. 새로운 기능을 제안하려 하는 것이라면, 그러한 것을 통해서 무엇을 개선하려 하는지 정확히 밝히는 것이 중요합니다. 사실, 해결책보다 그것이 더 중요합니다.

섹션 번호는 생략해주시기 바랍니다. 번호는 자주 바뀌므로, 피드백을 이해하기가 더 어려워집니다.

Please don't use section numbers as these tend to change rapidly and make your feedback harder to understand.

(Note: 스팸을 방지할 목적으로 IP 주소를 기록할 것입니다.)

이 폼을 이용할 수 없을 경우, public-html-comments@w3.org로 피드백을 보낼 수 있습니다. (구독목록) 이렇게 전달된 피드백은 공개된 버그 데이터베이스에 기록될 것입니다. 또는 whatwg@whatwg.org로 메일을 보내도 됩니다. (구독목록). 편집자는 이 목록으로 전달된 모든 실질적인 피드백에 응답할 것을 보장합니다만, 그러한 피드백은 공식적인 것으로 간주되지는 않습니다. 모든 피드백을 환영합니다.

If you cannot do this then you can also e-mail feedback to public-html-comments@w3.org (subscribearchives), and arrangements will be made to transpose the comments to our public bug database. Alternatively, you can e-mail feedback to whatwg@whatwg.org (subscribe,archives). The editor guarantees that all substantive feedback sent to this list will receive a reply. However, such feedback is not considered formal feedback for the W3C process. All feedback is welcome.

워킹 그룹에서는 아직 편집자가 교정을 시도하지 않은 버그 리포트와, 아직 대응방안이 결정되지 않은 이슈들의 목록을 유지하고 있습니다. 편집자는 아직 검토하지 못한 이메일 목록 역시 관리하고 있습니다. 이러한 버그, 이슈, 이메일들은 단순히 이 명세뿐만이 아니라, HTML에 관련된 다양한 명세들에 적용됩니다.

The working groups maintains a list of all bug reports that the editor has not yet tried to address and a list of issues for which the chairs have not yet declared a decision. The editor also maintains a list of all e-mails that he has not yet tried to address. These bugs, issues, and e-mails apply to multiple HTML-related specifications, not just this one.

구현자implementor들은 이 명세가 아직 안정된 상태가 아님을 명심해야 합니다. 토론에 참여하지 않은 구현자들은 명세가 비호환적인 방향으로 변경되는 것을 발견할 것입니다. 이 명세를 구현하고자 하는 제작자들은 명세가 권고 후보 단계에 도달하기 전에 상기 메일링 리스트에 가입하고 토론에 참여해야 합니다.

Implementors should be aware that this specification is not stable. Implementors who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation stage should join the aforementioned mailing lists and take part in the discussions.

이것은 진행중인 명세입니다! HTML 워킹 그룹의 최신 업데이트 - 중요한 버그 픽스를 포함하고 있을 수 있습니다 - 를 보려면 편집자 초안을 보기 바랍니다.

This is a work in progress! For the latest updates from the HTML WG, possibly including important bug fixes, please look at the editor's draft instead.

이 문서를 W3C 워킹 드래프트로 발행한다고 해서, W3C HTML 워킹 그룹의 참여자들 모두가 이 명세의 내용을 존중한다는 것을 암시하지는 않습니다. 물론, 이 명세의 모든 섹션에 대해 워킹 그룹 혹은 W3C 멤버들 중 많은 사람이 현재의 텍스트를 충실히 따르고 섹션 전체를 존중하거나, 최소한 섹션의 컨셉을 토의하는데 시간을 투자해야 한다는 점에 의견을 같이하고 있습니다.

The publication of this document by the W3C as a W3C Working Draft does not imply that all of the participants in the W3C HTML working group endorse the contents of the specification. Indeed, for any section of the specification, one can usually find many members of the working group or of the W3C as a whole who object strongly to the current text, the existence of the section at all, or the idea that the working group should even spend time discussing the concept of that section.

이 명세의 안정화된 최근 편집자 초안은 the W3C CVS serverWHATWG Subversion repository에서 이용할 수 있습니다. 최근의 편집자 카피 (완결되지 않은 문장이 들어 있을 수 있습니다)에는 이 명세와 관련된 최근의 초안 텍스트들이 포함되어 있습니다. 더 자세한 내용은 WHATWG FAQ을 참고하기 바랍니다.

The latest stable version of the editor's draft of this specification is always available on the W3C CVS server and in the WHATWG Subversion repository. The latest editor's working copy (which may contain unfinished text in the process of being prepared) contains the latest draft text of this specification (amongst others). For more details, please see the WHATWG FAQ.

HTML 명세의 변경 이력은 다음과 같은 방법으로 열람할 수 있습니다.

There are various ways to follow the change history for the HTML specifications:

E-mail notifications of changes
HTML-Diffs mailing list (diff-marked HTML versions for each change): http://lists.w3.org/Archives/Public/public-html-diffs/latest

Commit-Watchers mailing list (complete source diffs): http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org

Real-time notifications of changes:
Generated diff-marked HTML versions for each change: http://twitter.com/HTML5

Browsable version-control record of all changes:
CVSWeb interface with side-by-side diffs: http://dev.w3.org/cvsweb/html5/

Annotated summary with unified diffs: http://html5.org/tools/web-apps-tracker

Raw Subversion interface: svn checkout http://svn.whatwg.org/webapps/

W3C의 HTML 워킹 그룹에서 W3C 권고안 트랙에 관련하여 이 명세의 진행을 책임지고 있습니다. 이 명세는 2011년 1월 13일자 초안입니다.

The W3C HTML Working Group is the W3C working group responsible for this specification's progress along the W3C Recommendation track. This specification is the 13 January 2011 Working Draft.

WHATWG에서도 이 명세에 관한 작업을 진행하고 있습니다. W3C HTML 워킹그룹은 WHATWG와 협력하고 있으며, 이에 관한 상세는 W3C HTML working group charter에 있습니다.

Work on this specification is also done at the WHATWG. The W3C HTML working group actively pursues convergence with the WHATWG, as required by the W3C HTML working group charter.

이 문서는 2004년 2월 5일 W3C 특허 정책을 준용합니다. W3C는 그룹의 운영과 관련하여 공적인 특허 목록을 관리합니다. 이 페이지에는 특허를 발표하는 것에 관한 지침 역시 포함되어 있습니다.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

차례

아래의 차례에서 회색으로 표시된 부분은 그 내용이 브라우저 제작자 대상이며, 따라서 번역되지 않았음을 나타냅니다.
+ 가 표시된 부분은 하위 메뉴가 있음을 나타냅니다. 클릭하면 하위 메뉴가 펼쳐집니다.

  1. 1 소개
    1. 1.1 배경
    2. 1.2 대상 독자
    3. 1.3 초점
    4. 1.4 역사
    5. 1.5 디자인 노트
      1. 1.5.1 스크립트 실행의 직렬화
      2. 1.5.2 다른 명세와의 관계
    6. 1.6 HTML 과 XHTML
    7. 1.7 명세의 구조
      1. 1.7.1 명세를 읽는 방법
      2. 1.7.2 표현 방법
    8. 1.8 HTML에 대한 간단한 소개
    9. 1.9 저자가 지켜야 할 것
      1. 1.9.1 표현적 마크업
      2. 1.9.2 문법 에러
      3. 1.9.3 내용 모델과 속성값에 대한 제한들
    10. 1.10 읽을만한 것들
  2. 2 공통 의미구조

    명세 전반에 걸쳐 사용될 클래스, 알고리즘, 정의, 그리고 기반구조들입니다.

    1. 2.1 단어 사용
      1. 2.1.1 자원
      2. 2.1.2 XML
      3. 2.1.3 DOM 트리
      4. 2.1.4 스크립팅
      5. 2.1.5 플러그인
      6. 2.1.6 문자 인코딩
    2. 2.2 이행 요구사항
      1. 2.2.1 종속성
      2. 2.2.2 확장성
    3. 2.3 대소문자 구분과 문자열 비교
    4. 2.4 UTF-8
    5. 2.5 공통 상세문법
      1. 2.5.1 파서 숙어
      2. 2.5.2 불리언 속성
      3. 2.5.3 키워드, 나열 속성
      4. 2.5.4 숫자
        1. 2.5.4.1 음이 아닌 정수
        2. 2.5.4.2 기호가 붙은 정수
        3. 2.5.4.3 실수
        4. 2.5.4.4 퍼센트와 길이
        5. 2.5.4.5 정수 목록
        6. 2.5.4.6 크기 목록
      5. 2.5.5 날짜와 시간
        1. 2.5.5.1 월
        2. 2.5.5.2 일
        3. 2.5.5.3 시간
        4. 2.5.5.4 날짜와 시간(지역)
        5. 2.5.5.5 날짜와 시간(국제)
        6. 2.5.5.6 주
        7. 2.5.5.7 모호한 시간
      6. 2.5.6 색상
      7. 2.5.7 공백문자로 구분된 토큰
      8. 2.5.8 쉼표로 구분된 토큰
      9. 2.5.9 참조
      10. 2.5.10 미디어 쿼리
    6. 2.6 URL
      1. 2.6.1 단어 사용
      2. 2.6.2 기본 URL의 동적 변화
      3. 2.6.3 URL 조작 인터페이스
    7. 2.7 자원 다운로드
      1. 2.7.1 프로토콜 컨셉
      2. 2.7.2 암호화된 HTTP, 관련된 보안 문제
      3. 2.7.3 자원 타입의 판별
    8. 2.8 공통 DOM 인터페이스
      1. 2.8.1 IDL 속성에서 내용 속성의 반영
      2. 2.8.2 컬렉션
        1. 2.8.2.1 HTMLCollection
        2. 2.8.2.2 HTMLAllCollection
        3. 2.8.2.3 HTMLFormControlsCollection
        4. 2.8.2.4 HTMLOptionsCollection
      3. 2.8.3 DOMTokenList
      4. 2.8.4 DOMSettableTokenList
      5. 2.8.5 구조화된 데이터의 안전한 전달
      6. 2.8.6 DOMStringMap
      7. 2.8.7 DOM 기능 문자열
      8. 2.8.8 예외
      9. 2.8.9 메모리 반환
    9. 2.9 네임스페이스
  3. 3 HTML 문서의 의미, 구조, API

    문서는 요소들로 구성됩니다. 이러한 요소들은 DOM을 통해 트리 구조를 가집니다. 이 섹션은 이러한 DOM의 기능들을 정의하며, 또한 모든 요소들에 공통되는 기능을 정의하고, 요소를 정의하는데 사용되는 컨셉들을 설명합니다.

    1. 3.1 문서
      1. 3.1.1 DOM 내부의 문서
      2. 3.1.2 보안
      3. 3.1.3 자원 메타데이터 관리
      4. 3.1.4 DOM 트리 접근자
      5. 3.1.5 문서 생성
      6. 3.1.6 XML 문서 로딩
    2. 3.2 요소
      1. 3.2.1 의미론
      2. 3.2.2 DOM 내부의 요소
      3. 3.2.3 전역 속성
        1. 3.2.3.1 id 속성
        2. 3.2.3.2 title 속성
        3. 3.2.3.3 langxml:lang 속성
        4. 3.2.3.4 xml:base attribute (XML only)
        5. 3.2.3.5 dir 속성
        6. 3.2.3.6 class 속성
        7. 3.2.3.7 style 속성
        8. 3.2.3.8 data-* 속성을 이용한 보이지 않는 커스텀 데이터 사용
      4. 3.2.4 요소 정의
        1. 3.2.4.1 속성
      5. 3.2.5 내용 모델
        1. 3.2.5.1 내용의 종류
          1. 3.2.5.1.1메타데이터
          2. 3.2.5.1.2 플로우 컨텐츠
          3. 3.2.5.1.3 섹션 컨텐츠
          4. 3.2.5.1.4 제목 컨텐츠
          5. 3.2.5.1.5구문 컨텐츠
          6. 3.2.5.1.6 포함된 컨텐츠
          7. 3.2.5.1.7 대화형 컨텐츠
        2. 3.2.5.2 투명한 컨텐츠 모델
        3. 3.2.5.3 문단
      6. 3.2.6 양방향 알고리즘 포맷 문자에 관한 요구사항
      7. 3.2.7 보조 기술 제품을 위한 주석 (ARIA)
    3. 3.3 HTML 문서의 API

    4. 3.4 XPath, XSLT 와의 상호작용
    5. 3.5 동적 마크업 삽입
      1. 3.5.1 입력 스트림 열기
      2. 3.5.2 입력 스트림 닫기
      3. 3.5.3 document.write()
      4. 3.5.4 document.writeln()
      5. 3.5.5 innerHTML
      6. 3.5.6 outerHTML
      7. 3.5.7 insertAdjacentHTML()
  4. 4 HTML의 요소

    각각의 요소들은 미리 정의된 의미를 가지며, 이 섹션에서 그것들을 설명합니다. 저자들이 이 요소를 어떻게 사용해야 할지 역시 설명합니다.

    1. 4.1 The root element
      1. 4.1.1 html 요소
    2. 4.2 문서의 메타데이터
      1. 4.2.1 head 요소
      2. 4.2.2 title 요소
      3. 4.2.3 base 요소
      4. 4.2.4 link 요소
      5. 4.2.5 meta 요소
        1. 4.2.5.1 표준 메타데이터 이름
        2. 4.2.5.2 기타 메타데이터 이름
        3. 4.2.5.3 프라그마 디렉티브
        4. 4.2.5.4 기타 프라그마 디렉티브
        5. 4.2.5.5 문서의 문자 인코딩 명시
      6. 4.2.6 style 요소
      7. 4.2.7 스타일링
    3. 4.3 스크립팅
      1. 4.3.1 script 요소
        1. 4.3.1.1 스크립트 언어
        2. 4.3.1.2 요소의 내용 제한
        3. 4.3.1.3 외부 스크립트에 대한 인라인 문서화
      2. 4.3.2 noscript 요소
    4. 4.4 섹션
      1. 4.4.1 body 요소
      2. 4.4.2 section 요소
      3. 4.4.3 nav 요소
      4. 4.4.4 article 요소
      5. 4.4.5 aside 요소
      6. 4.4.6 h1h2h3h4h5h6 요소
      7. 4.4.7 hgroup 요소
      8. 4.4.8 header 요소
      9. 4.4.9 footer 요소
      10. 4.4.10 address 요소
      11. 4.4.11 제목과 섹션
        1. 4.4.11.1 개요 작성
    5. 4.5 그룹 컨텐츠
      1. 4.5.1 p 요소
      2. 4.5.2 hr 요소
      3. 4.5.3 pre 요소
      4. 4.5.4 blockquote 요소
      5. 4.5.5 ol 요소
      6. 4.5.6 ul 요소
      7. 4.5.7 li 요소
      8. 4.5.8 dl 요소
      9. 4.5.9 dt 요소
      10. 4.5.10 dd 요소
      11. 4.5.11 figure 요소
      12. 4.5.12 figcaption 요소
      13. 4.5.13 div 요소
    6. 4.6 텍스트 레벨 의미론
      1. 4.6.1 a 요소
      2. 4.6.2 em 요소
      3. 4.6.3 strong 요소
      4. 4.6.4 small 요소
      5. 4.6.5 s 요소
      6. 4.6.6 cite 요소
      7. 4.6.7 q 요소
      8. 4.6.8 dfn 요소
      9. 4.6.9 abbr 요소
      10. 4.6.10 time 요소
      11. 4.6.11 code 요소
      12. 4.6.12 var 요소
      13. 4.6.13 samp 요소
      14. 4.6.14 kbd 요소
      15. 4.6.15 subsup 요소
      16. 4.6.16 i 요소
      17. 4.6.17 b 요소
      18. 4.6.18 mark 요소
      19. 4.6.19 ruby 요소
      20. 4.6.20 rt 요소
      21. 4.6.21 rp 요소
      22. 4.6.22 bdi 요소
      23. 4.6.23 bdo 요소
      24. 4.6.24 span 요소
      25. 4.6.25 br 요소
      26. 4.6.26 wbr 요소
      27. 4.6.27 사용법 요약
    7. 4.7 편집
      1. 4.7.1 ins 요소
      2. 4.7.2 del 요소
      3. 4.7.3 insdel 요소에 공통인 속성
      4. 4.7.4 편집과 문단
      5. 4.7.5 편집과 목록
    8. 4.8 포함된 컨텐츠
      1. 4.8.1 img 요소
        1. 4.8.1.1 이미지에 대한 대체로 사용될 텍스트를 제공하는 것에 대한 요구사항
          1. 4.8.1.1.1 범용 가이드라인
          2. 4.8.1.1.2 이미지만을 포함하는 링크 혹은 버튼
          3. 4.8.1.1.3 대체적인 그래픽 표현 - 차트, 다이어그램, 그래프, 지도, 일러스트레이션 - 을 갖는 구문이나 문단
          4. 4.8.1.1.4 대체적인 그래픽 표현 - 아이콘, 로고 - 을 갖는 짧은 구문이나 레이블
          5. 4.8.1.1.5 글자 표현 효과를 위해 그래픽으로 렌더링된 텍스트
          6. 4.8.1.1.6 주위 텍스트 일부를 그래픽으로 표현한 것
          7. 4.8.1.1.7 아무런 정보도 전달하지 않는 순수한 장식적 이미지
          8. 4.8.1.1.8 링크를 형성하지 않는, 더 큰 하나의 이미지를 형성하는 이미지 그룹
          9. 4.8.1.1.9 링크를 형성하는, 더 큰 하나의 이미지를 형성하는 이미지 그룹
          10. 4.8.1.1.10 내용의 핵심 파트
          11. 4.8.1.1.11 사용자에게 보일 의도가 없는 이미지
          12. 4.8.1.1.12 이미지를 볼 수 있음을 알고 있는 특정한 사람이 볼 것으로 의도된 이메일, 또는 사적인 문서에 포함된 이미지
          13. 4.8.1.1.13 마크업 생성기를 위한 가이드
          14. 4.8.1.1.14 유효성 검사기를 위한 가이드
      2. 4.8.2 iframe 요소
      3. 4.8.3 embed 요소
      4. 4.8.4 object 요소
      5. 4.8.5 param 요소
      6. 4.8.6 video 요소
      7. 4.8.7 audio 요소
      8. 4.8.8 source 요소
      9. 4.8.9 track 요소
      10. 4.8.10 Media 요소
        1. 4.8.10.1 에러 코드
        2. 4.8.10.2 미디어 자원의 위치
        3. 4.8.10.3 마임 타입
        4. 4.8.10.4 네트워크 상태
        5. 4.8.10.5 미디어 자원 로딩
        6. 4.8.10.6 미디어 자원으로의 오프셋
        7. 4.8.10.7 "준비됨" 상태
        8. 4.8.10.8 미디어 자원 재생
        9. 4.8.10.9 탐색
        10. 4.8.10.10 시간이 설정된 텍스트 트랙
          1. 4.8.10.10.1 텍스트 트랙 모델
          2. 4.8.10.10.2 Sourcing in-band text tracks
          3. 4.8.10.10.3 Sourcing out-of-band text tracks
          4. 4.8.10.10.4 텍스트 트랙 API
          5. 4.8.10.10.5 이벤트 정의
        11. 4.8.10.11 사용자 인터페이스
        12. 4.8.10.12 시간 범위
        13. 4.8.10.13 이벤트 요약
        14. 4.8.10.14 보안과 프라이버시에 관한 고려
        15. 4.8.10.15 미디어 요소 구현의 모범 사례(웹 저자)
        16. 4.8.10.16 미디어 요소 구현의 모범 사례(구현자)
      11. 4.8.11 canvas 요소
        1. 4.8.11.1 색상 범위와 수정
        2. 4.8.11.2 canvas 요소에서의 보안
      12. 4.8.12 map 요소
      13. 4.8.13 area 요소
      14. 4.8.14 이미지 맵
        1. 4.8.14.1 저작
        2. 4.8.14.2 처리모델
      15. 4.8.15 MathML
      16. 4.8.16 SVG
      17. 4.8.17 크기 속성
    9. 4.9 표 형태의 데이터
      1. 4.9.1 table 요소
      2. 4.9.2 caption 요소
      3. 4.9.3 colgroup 요소
      4. 4.9.4 col 요소
      5. 4.9.5 tbody 요소
      6. 4.9.6 thead 요소
      7. 4.9.7 tfoot 요소
      8. 4.9.8 tr 요소
      9. 4.9.9 td 요소
      10. 4.9.10 th 요소
      11. 4.9.11 tdth 공통적인 속성
      12. 4.9.12 처리 모델
        1. 4.9.12.1 테이블 포맷
        2. 4.9.12.2 데이터 셀과 헤더 셀 사이의 연결 생성
      13. 4.9.13 예제
    10. 4.10 Forms
      1. 4.10.1 소개
        1. 4.10.1.1 사용자 인터페이스 작성
        2. 4.10.1.2 서버사이드 처리 구현
        3. 4.10.1.3 서버와 통신하도록 설정
        4. 4.10.1.4 클라이언트 사이드 유효성 검사
      2. 4.10.2 분류
      3. 4.10.3 form 요소
      4. 4.10.4 fieldset 요소
      5. 4.10.5 legend 요소
      6. 4.10.6 label 요소
      7. 4.10.7 input 요소
        1. 4.10.7.1 type 속성의 상태
          1. 4.10.7.1.1 Hidden state
          2. 4.10.7.1.2 Text state, Search state
          3. 4.10.7.1.3 Telephone state
          4. 4.10.7.1.4 URL state
          5. 4.10.7.1.5 E-mail state
          6. 4.10.7.1.6 Password state
          7. 4.10.7.1.7 Date and Time state
          8. 4.10.7.1.8 Date state
          9. 4.10.7.1.9 Month state
          10. 4.10.7.1.10 Week state
          11. 4.10.7.1.11 Time state
          12. 4.10.7.1.12 Local Date and Time state
          13. 4.10.7.1.13 Number state
          14. 4.10.7.1.14 Range state
          15. 4.10.7.1.15 Color state
          16. 4.10.7.1.16 Checkbox state
          17. 4.10.7.1.17 Radio Button state
          18. 4.10.7.1.18 File Upload state
          19. 4.10.7.1.19 Submit Button state
          20. 4.10.7.1.20 Image Button state
          21. 4.10.7.1.21 Reset Button state
          22. 4.10.7.1.22 Button state
        2. 4.10.7.2 input 요소의 공통 속성
          1. 4.10.7.2.1 autocomplete 속성
          2. 4.10.7.2.2 dirname 속성
          3. 4.10.7.2.3 list 속성
          4. 4.10.7.2.4 readonly 속성
          5. 4.10.7.2.5 size 속성
          6. 4.10.7.2.6 required 속성
          7. 4.10.7.2.7 multiple 속성
          8. 4.10.7.2.8 maxlength 속성
          9. 4.10.7.2.9 pattern 속성
          10. 4.10.7.2.10 minmax 속성
          11. 4.10.7.2.11 step 속성
          12. 4.10.7.2.12 placeholder 속성
        3. 4.10.7.3 input 요소의 공통 API
        4. 4.10.7.4 공통 이벤트 행동
      8. 4.10.8 button 요소
      9. 4.10.9 select 요소
      10. 4.10.10 datalist 요소
      11. 4.10.11 optgroup 요소
      12. 4.10.12 option 요소
      13. 4.10.13 textarea 요소
      14. 4.10.14 keygen 요소
      15. 4.10.15 output 요소
      16. 4.10.16 progress 요소
      17. 4.10.17 meter 요소
      18. 4.10.18 컨트롤과 폼의 연결
      19. 4.10.19 폼 컨트롤에 공통된 속성
        1. 4.10.19.1 폼 컨트롤 명명
        2. 4.10.19.2 폼 컨트롤의 활성화 및 비활성화
        3. 4.10.19.3 컨트롤의 값
        4. 4.10.19.4 컨트롤에 자동으로 포커스 주기
        5. 4.10.19.5 사용자 입력의 길이 제한
        6. 4.10.19.6 폼 제출
        7. 4.10.19.7 요소 방향성 제출
      20. 4.10.20 텍스트 필드 선택을 위한 API
      21. 4.10.21 제약조건
        1. 4.10.21.1 정의
        2. 4.10.21.2 제약사항 검사
        3. 4.10.21.3 제약사항 검사 API
        4. 4.10.21.4 보안
      22. 4.10.22 폼 제출
        1. 4.10.22.1 소개
        2. 4.10.22.2 암시적인 제출
        3. 4.10.22.3 폼 제출 알고리즘
        4. 4.10.22.4 URL로 인코드된 폼 데이터
        5. 4.10.22.5 멀티파트 폼 데이터
        6. 4.10.22.6 단순 텍스트 폼 데이터
      23. 4.10.23 폼 리셋
      24. 4.10.24 이벤트 전달
    11. 4.11 인터랙티브 요소
      1. 4.11.1 details 요소
      2. 4.11.2 summary 요소
      3. 4.11.3 command 요소
      4. 4.11.4 menu 요소
        1. 4.11.4.1 소개
        2. 4.11.4.2 메뉴와 툴바 생성
        3. 4.11.4.3 컨텍스트 메뉴
        4. 4.11.4.4 툴바
      5. 4.11.5 Commands
        1. 4.11.5.1 a 요소로 커맨드 정의
        2. 4.11.5.2 button 요소로 커맨드 정의
        3. 4.11.5.3 input 요소로 커맨드 정의
        4. 4.11.5.4 option 요소로 커맨드 정의
        5. 4.11.5.5 command 요소로 커맨드 정의
        6. 4.11.5.6 label 요소의 accesskey속성으로 커맨드 정의
        7. 4.11.5.7 legend 요소의 accesskey 속성으로 커맨드 정의
        8. 4.11.5.8 다른 요소의 accesskey 속성으로 커맨드 정의
    12. 4.12 링크
      1. 4.12.1 소개
      2. 4.12.2 a 요소와 area 요소로 생성된 링크
      3. 4.12.3 하이퍼링크 따라가기
      4. 4.12.4 링크 타입
        1. 4.12.4.1 Link type "alternate"
        2. 4.12.4.2 Link type "archives"
        3. 4.12.4.3 Link type "author"
        4. 4.12.4.4 Link type "bookmark"
        5. 4.12.4.5 Link type "external"
        6. 4.12.4.6 Link type "help"
        7. 4.12.4.7 Link type "icon"
        8. 4.12.4.8 Link type "license"
        9. 4.12.4.9 Link type "nofollow"
        10. 4.12.4.10 Link type "noreferrer"
        11. 4.12.4.11 Link type "pingback"
        12. 4.12.4.12 Link type "prefetch"
        13. 4.12.4.13 Link type "search"
        14. 4.12.4.14 Link type "stylesheet"
        15. 4.12.4.15 Link type "sidebar"
        16. 4.12.4.16 Link type "tag"
        17. 4.12.4.17 계층형 링크 타입
          1. 4.12.4.17.1 Link type "index"
          2. 4.12.4.17.2 Link type "up"
        18. 4.12.4.18 연속적인 링크 타입
          1. 4.12.4.18.1 Link type "first"
          2. 4.12.4.18.2 Link type "last"
          3. 4.12.4.18.3 Link type "next"
          4. 4.12.4.18.4 Link type "prev"
        19. 4.12.4.19 다른 링크 타입
    13. 4.13 전용 요소는 없지만 일반적인 숙어들
      1. 4.13.1 내용의 주된 파트
      2. 4.13.2 태그 클라우드
      3. 4.13.3 대화
      4. 4.13.4 각주
    14. 4.14 셀렉터를 사용하여 HTML 요소 매칭
      1. 4.14.1 대소문자 구분
      2. 4.14.2 가상 클래스
  5. 5 웹 페이지 로딩

    HTML 문서는 진공 속에 존재하는 것이 아닙니다. 이 섹션은 다양한 문서들을 다루는 환경들에 영향을 미치는 기능들을 설명합니다.

    1. 5.1 브라우징 문맥
      1. 5.1.1 중첩된 브라우징 문맥
        1. 5.1.1.1 DOM에서 중첩된 브라우징 문맥 이동
      2. 5.1.2 보조 브라우징 문맥
        1. 5.1.2.1 DOM에서 보조 브라우징 문맥 이동
      3. 5.1.3 두번째 브라우징 문맥
      4. 5.1.4 보안
      5. 5.1.5 브라우징 문맥 그룹화
      6. 5.1.6 브라우징 문맥 이름
    2. 5.2 Window object
      1. 5.2.1 보안
      2. 5.2.2 이름을 사용해서 브라우징 문맥을 생성하고 탐색하는 API
      3. 5.2.3 다른 브라우징 문맥 접근
      4. 5.2.4 Window 객체에 이름으로 접근
      5. 5.2.5 가비지 컬렉션과 브라우징 문맥
      6. 5.2.6 브라우저 인터페이스 요소
      7. 5.2.7 WindowProxy object
    3. 5.3 Origin
      1. 5.3.1 동일 소스 제한 완화
    4. 5.4 세션 히스토리와 이동
      1. 5.4.1 브라우징 문맥의 세션 히스토리
      2. 5.4.2 History interface
      3. 5.4.3 Location interface
        1. 5.4.3.1 보안
      4. 5.4.4 세션 히스토리 구현 노트
    5. 5.5 웹 브라우징
      1. 5.5.1 문서들간의 이동
      2. 5.5.2 HTML 파일의 페이지 로드 처리 모델
      3. 5.5.3 XML 파일의 페이지 로드 처리 모델
      4. 5.5.4 텍스트 파일의 페이지 로드 처리 모델
      5. 5.5.5 이미지의 페이지 로드 처리 모델
      6. 5.5.6 플러그인을 사용하는 컨텐츠의 페이지 로드 처리 모델
      7. 5.5.7 DOM 을 갖지 않는 인라인 컨텐츠의 페이지 로드 처리 모델
      8. 5.5.8 조각 식별자(#)로 이동
      9. 5.5.9 히스토리 이동
        1. 5.5.9.1 이벤트 정의
      10. 5.5.10 문서 언로드
        1. 5.5.10.1 이벤트 정의
      11. 5.5.11 문서 로드 취소
    6. 5.6 오프라인 웹 어플리케이션
      1. 5.6.1 소개
        1. 5.6.1.1 이벤트 요약
      2. 5.6.2 어플리케이션 캐쉬
      3. 5.6.3 캐쉬 매니페스트 문법
        1. 5.6.3.1 매니페스트 샘플
        2. 5.6.3.2 캐쉬 매니페스트 작성
        3. 5.6.3.3 캐쉬 매니페스트 처리
      4. 5.6.4 어플리케이션 캐쉬의 다운로드 또는 업데이트
      5. 5.6.5 어플리케이션 캐쉬 선택 알고리즘
      6. 5.6.6 네트워크 모델의 변경
      7. 5.6.7 어플리케이션 캐쉬 만료
      8. 5.6.8 디스크 용량
      9. 5.6.9 어플리케이션 캐쉬 API
      10. 5.6.10 브라우저 상태
  6. 6 웹 어플리케이션 API

    이 섹션은 HTML 어플리케이션의 스크립팅을 위한 간단한 기능들을 소개합니다.

    1. 6.1 스크립팅
      1. 6.1.1 소개
      2. 6.1.2 스크립팅 허용과 금지
      3. 6.1.3 처리 모델
        1. 6.1.3.1 정의
        2. 6.1.3.2 스크립트 호출
        3. 6.1.3.3 스크립트 생성
        4. 6.1.3.4 스크립트 중지
      4. 6.1.4 이벤트 루프
        1. 6.1.4.1 정의
        2. 6.1.4.2 처리 모델
        3. 6.1.4.3 범용 작업 소스
      5. 6.1.5 javascript: 프로토콜
      6. 6.1.6 이벤트
        1. 6.1.6.1 이벤트 핸들러
        2. 6.1.6.2 요소, Document 객체, Window 객체의 이벤트 핸들러
        3. 6.1.6.3 이벤트 발생
        4. 6.1.6.4 이벤트와 Window 객체
        5. 6.1.6.5 런타임 스크립트 에러
    2. 6.2 타이머
    3. 6.3 사용자 프롬프트
      1. 6.3.1 간단한 대화상자
      2. 6.3.2 인쇄
      3. 6.3.3 별도의 창을 이용해 구현된 대화상자
    4. 6.4 시스템 상태와 가용성: Navigator 객체
      1. 6.4.1 클라이언트 식별
      2. 6.4.2 커스텀 스키마와 내용 핸들러
        1. 6.4.2.1 보안과 프라이버시
        2. 6.4.2.2 사용자 인터페이스 예제
      3. 6.4.3 저장소간 상호 배제의 수동 해제
  7. 7 사용자 인터랙션

    HTML 문서들은 사용자들이 컨텐츠와 상호작용하고 그것을 변경할 수 있는 다양한 메커니즘들을 제공할 수 있습니다. 이 섹션에서 그것들을 설명합니다.

    1. 7.1 hidden 속성
    2. 7.2 활성화
    3. 7.3 포커스
      1. 7.3.1 순서있는 포커스 이동과 tabindex 속성
      2. 7.3.2 포커스 관리
      3. 7.3.3 문서 레벨의 포커스 API
      4. 7.3.4 요소 레벨의 포커스 API
    4. 7.4 키보드 단축키 할당
      1. 7.4.1 소개
      2. 7.4.2 accesskey 속성
      3. 7.4.3 처리 모델
    5. 7.5 contenteditable 속성
      1. 7.5.1 사용자의 편집 동작
      2. 7.5.2 문서 전체를 편집 가능하도록 만들기
    6. 7.6 철자와 문법 체크
    7. 7.7 드래그-드롭
      1. 7.7.1 소개
      2. 7.7.2 드래그 데이터 저장
      3. 7.7.3 DataTransfer 인터페이스
        1. 7.7.3.1 DataTransferItems 인터페이스
        2. 7.7.3.2 DataTransferItem 인터페이스
      4. 7.7.4 DragEvent 인터페이스
      5. 7.7.5 드래그-드롭 처리 모델
      6. 7.7.6 이벤트 요약
      7. 7.7.7 draggable 속성
      8. 7.7.8 dropzone 속성
      9. 7.7.9 드래그-드롭 모델의 보안 위험성
    8. 7.8 편집 API
  8. 8 The HTML 문법

    이 섹션에서는 HTML의 문법들을 정의하며, 컨텐츠들을 그러한 문법들을 사용해 파싱하는 규칙을 정의할 것입니다.

    1. 8.1 HTML 문서 작성
      1. 8.1.1 The DOCTYPE
      2. 8.1.2 요소
        1. 8.1.2.1 시작 태그
        2. 8.1.2.2 종료 태그
        3. 8.1.2.3 속성
        4. 8.1.2.4 선택적 태그
        5. 8.1.2.5 내용 모델의 제한사항
        6. 8.1.2.6 텍스트 원형과 RCDATA 요소 내용에 대한 제한
      3. 8.1.3 텍스트
        1. 8.1.3.1 줄바꿈
      4. 8.1.4 문자 참조
      5. 8.1.5 CDATA 섹션
      6. 8.1.6 주석
    2. 8.2 HTML 문서 처리
      1. 8.2.1 Overview of the parsing model
      2. 8.2.2 The input stream
        1. 8.2.2.1 Determining the character encoding
        2. 8.2.2.2 Character encodings
        3. 8.2.2.3 Preprocessing the input stream
        4. 8.2.2.4 Changing the encoding while parsing
      3. 8.2.3 Parse state
        1. 8.2.3.1 The insertion mode
        2. 8.2.3.2 The stack of open elements
        3. 8.2.3.3 The list of active formatting elements
        4. 8.2.3.4 The element pointers
        5. 8.2.3.5 Other parsing state flags
      4. 8.2.4 Tokenization
        1. 8.2.4.1 Data state
        2. 8.2.4.2 Character reference in data state
        3. 8.2.4.3 RCDATA state
        4. 8.2.4.4 Character reference in RCDATA state
        5. 8.2.4.5 RAWTEXT state
        6. 8.2.4.6 Script data state
        7. 8.2.4.7 PLAINTEXT state
        8. 8.2.4.8 Tag open state
        9. 8.2.4.9 End tag open state
        10. 8.2.4.10 Tag name state
        11. 8.2.4.11 RCDATA less-than sign state
        12. 8.2.4.12 RCDATA end tag open state
        13. 8.2.4.13 RCDATA end tag name state
        14. 8.2.4.14 RAWTEXT less-than sign state
        15. 8.2.4.15 RAWTEXT end tag open state
        16. 8.2.4.16 RAWTEXT end tag name state
        17. 8.2.4.17 Script data less-than sign state
        18. 8.2.4.18 Script data end tag open state
        19. 8.2.4.19 Script data end tag name state
        20. 8.2.4.20 Script data escape start state
        21. 8.2.4.21 Script data escape start dash state
        22. 8.2.4.22 Script data escaped state
        23. 8.2.4.23 Script data escaped dash state
        24. 8.2.4.24 Script data escaped dash dash state
        25. 8.2.4.25 Script data escaped less-than sign state
        26. 8.2.4.26 Script data escaped end tag open state
        27. 8.2.4.27 Script data escaped end tag name state
        28. 8.2.4.28 Script data double escape start state
        29. 8.2.4.29 Script data double escaped state
        30. 8.2.4.30 Script data double escaped dash state
        31. 8.2.4.31 Script data double escaped dash dash state
        32. 8.2.4.32 Script data double escaped less-than sign state
        33. 8.2.4.33 Script data double escape end state
        34. 8.2.4.34 Before attribute name state
        35. 8.2.4.35 Attribute name state
        36. 8.2.4.36 After attribute name state
        37. 8.2.4.37 Before attribute value state
        38. 8.2.4.38 Attribute value (double-quoted) state
        39. 8.2.4.39 Attribute value (single-quoted) state
        40. 8.2.4.40 Attribute value (unquoted) state
        41. 8.2.4.41 Character reference in attribute value state
        42. 8.2.4.42 After attribute value (quoted) state
        43. 8.2.4.43 Self-closing start tag state
        44. 8.2.4.44 Bogus comment state
        45. 8.2.4.45 Markup declaration open state
        46. 8.2.4.46 Comment start state
        47. 8.2.4.47 Comment start dash state
        48. 8.2.4.48 Comment state
        49. 8.2.4.49 Comment end dash state
        50. 8.2.4.50 Comment end state
        51. 8.2.4.51 Comment end bang state
        52. 8.2.4.52 DOCTYPE state
        53. 8.2.4.53 Before DOCTYPE name state
        54. 8.2.4.54 DOCTYPE name state
        55. 8.2.4.55 After DOCTYPE name state
        56. 8.2.4.56 After DOCTYPE public keyword state
        57. 8.2.4.57 Before DOCTYPE public identifier state
        58. 8.2.4.58 DOCTYPE public identifier (double-quoted) state
        59. 8.2.4.59 DOCTYPE public identifier (single-quoted) state
        60. 8.2.4.60 After DOCTYPE public identifier state
        61. 8.2.4.61 Between DOCTYPE public and system identifiers state
        62. 8.2.4.62 After DOCTYPE system keyword state
        63. 8.2.4.63 Before DOCTYPE system identifier state
        64. 8.2.4.64 DOCTYPE system identifier (double-quoted) state
        65. 8.2.4.65 DOCTYPE system identifier (single-quoted) state
        66. 8.2.4.66 After DOCTYPE system identifier state
        67. 8.2.4.67 Bogus DOCTYPE state
        68. 8.2.4.68 CDATA section state
        69. 8.2.4.69 Tokenizing character references
      5. 8.2.5 Tree construction
        1. 8.2.5.1 Creating and inserting elements
        2. 8.2.5.2 Closing elements that have implied end tags
        3. 8.2.5.3 Foster parenting
        4. 8.2.5.4 The "initial" insertion mode
        5. 8.2.5.5 The "before html" insertion mode
        6. 8.2.5.6 The "before head" insertion mode
        7. 8.2.5.7 The "in head" insertion mode
        8. 8.2.5.8 The "in head noscript" insertion mode
        9. 8.2.5.9 The "after head" insertion mode
        10. 8.2.5.10 The "in body" insertion mode
        11. 8.2.5.11 The "text" insertion mode
        12. 8.2.5.12 The "in table" insertion mode
        13. 8.2.5.13 The "in table text" insertion mode
        14. 8.2.5.14 The "in caption" insertion mode
        15. 8.2.5.15 The "in column group" insertion mode
        16. 8.2.5.16 The "in table body" insertion mode
        17. 8.2.5.17 The "in row" insertion mode
        18. 8.2.5.18 The "in cell" insertion mode
        19. 8.2.5.19 The "in select" insertion mode
        20. 8.2.5.20 The "in select in table" insertion mode
        21. 8.2.5.21 The "in foreign content" insertion mode
        22. 8.2.5.22 The "after body" insertion mode
        23. 8.2.5.23 The "in frameset" insertion mode
        24. 8.2.5.24 The "after frameset" insertion mode
        25. 8.2.5.25 The "after after body" insertion mode
        26. 8.2.5.26 The "after after frameset" insertion mode
      6. 8.2.6 The end
      7. 8.2.7 Coercing an HTML DOM into an infoset
      8. 8.2.8 An introduction to error handling and strange cases in the parser
        1. 8.2.8.1 Misnested tags: <b><i></b></i>
        2. 8.2.8.2 Misnested tags: <b><p></b></p>
        3. 8.2.8.3 Unexpected markup in tables
        4. 8.2.8.4 Scripts that modify the page as it is being parsed
        5. 8.2.8.5 Unclosed formatting elements
    3. 8.3 Serializing HTML fragments
    4. 8.4 Parsing HTML fragments
    5. 8.5 Named character references
  9. 9 The XHTML 문법

    이 섹션에서는 XHTML의 문법들을 정의하며, 컨텐츠들을 그러한 문법들을 사용해 파싱하는 규칙을 정의할 것입니다.

    1. 9.1 Writing XHTML documents
    2. 9.2 Parsing XHTML documents
    3. 9.3 Serializing XHTML fragments
    4. 9.4 Parsing XHTML fragments
  10. 10 Rendering

    웹 브라우저들의 렌더링 규칙을 설명합니다.

    1. 10.1 Introduction
    2. 10.2 The CSS user agent style sheet and presentational hints
      1. 10.2.1 Introduction
      2. 10.2.2 Display types
      3. 10.2.3 Margins and padding
      4. 10.2.4 Alignment
      5. 10.2.5 Fonts and colors
      6. 10.2.6 Punctuation and decorations
      7. 10.2.7 Resetting rules for inherited properties
      8. 10.2.8 hr 요소
      9. 10.2.9 fieldset 요소
    3. 10.3 Replaced elements
      1. 10.3.1 Embedded content
      2. 10.3.2 Timed text tracks
        1. 10.3.2.1 WebVTT cue text rendering rules
        2. 10.3.2.2 Applying CSS properties to WebVTT Node Objects
        3. 10.3.2.3 CSS extensions
          1. 10.3.2.3.1 The '::cue' pseudo-element
          2. 10.3.2.3.2 The ':past' and ':future' pseudo-classes
      3. 10.3.3 Images
      4. 10.3.4 Attributes for embedded content and images
      5. 10.3.5 Image maps
      6. 10.3.6 Toolbars
    4. 10.4 Bindings
      1. 10.4.1 Introduction
      2. 10.4.2 button 요소
      3. 10.4.3 details 요소
      4. 10.4.4 input element as a text entry widget
      5. 10.4.5 input element as domain-specific widgets
      6. 10.4.6 input element as a range control
      7. 10.4.7 input element as a color well
      8. 10.4.8 input element as a check box and radio button widgets
      9. 10.4.9 input element as a file upload control
      10. 10.4.10 input element as a button
      11. 10.4.11 marquee 요소
      12. 10.4.12 meter 요소
      13. 10.4.13 progress 요소
      14. 10.4.14 select 요소
      15. 10.4.15 textarea 요소
      16. 10.4.16 keygen 요소
      17. 10.4.17 time 요소
    5. 10.5 Frames and framesets
    6. 10.6 Interactive media
      1. 10.6.1 Links, forms, navigation
      2. 10.6.2 title 속성
      3. 10.6.3 Editing hosts
      4. 10.6.4 Text rendered in native user interfaces
    7. 10.7 Print media
  11. 11 폐기된 기능들
    1. 11.1 폐기되었지만 올바른 기능들
      1. 11.1.1 폐기되었지만 올바른 기능들의 사용에 관한 경고
    2. 11.2 올바르지 않은 기능들
    3. 11.3 구현에 관한 요구사항
      1. 11.3.1 applet 요소
      2. 11.3.2 marquee 요소
      3. 11.3.3 Frames
      4. 11.3.4 그밖의 요소, 속성, API
  12. 12 IANA considerations
    1. 12.1 text/html
    2. 12.2 text/html-sandboxed
    3. 12.3 application/xhtml+xml
    4. 12.4 text/cache-manifest
  13. Index
    1. 요소
    2. Element content categories
    3. 속성
    4. Interfaces
    5. Events
  14. References
  15. Acknowledgements

Posted by 1010
반응형

1. ComboBox ItemRenderer

< ?xml version="1.0" encoding="utf-8"?>
< mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="450" height="370"
verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundColor="#FFFFFF">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable] public var initDG:ArrayCollection = new ArrayCollection([
{no:0, isChecked:"N"},
{no:1, isChecked:"Y"},
{no:2, isChecked:"N"},
{no:3, isChecked:"N"},
{no:4, isChecked:"Y"}]);
]]>
</mx:Script>
<mx:DataGrid id="myGrid" dataProvider="{initDG}" width="450" height="300" editable="false">
<mx:columns>
<mx:DataGridColumn headerText="no" dataField="no" width="150"/>
<mx:DataGridColumn headerText="isChecked" dataField="isChecked" width="150"/>
<mx:DataGridColumn dataField="isChecked" headerText="itemRenderer">
<mx:itemRenderer>
<mx:Component>
<mx:ComboBox selectedIndex="{data.isChecked=='Y'? 0:1}">
<mx:dataProvider>
<mx:Object label="Y" data="Y"/>
<mx:Object label="N" data="N"/>
</mx:dataProvider>
</mx:ComboBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
< /mx:Application>

2. CheckBox ItemRenderer
< ?xml version="1.0" encoding="utf-8"?>
< mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="450" height="370"
verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundColor="#FFFFFF">
<mx:Style>
global { font-size:12}
</mx:Style>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable] public var initDG:ArrayCollection = new ArrayCollection([
new RendererVO2(0, "N"),
new RendererVO2(1, "Y"),
new RendererVO2(2, "N"),
new RendererVO2(3, "N"),
new RendererVO2(4, "Y")]);
private var flag:Boolean = false;
private function checkAll():void {
if(flag) {
flag = false;
} else {
flag = true;
}
for(var idx:uint=0; idx<initDG.length; idx++) {
initDG[idx] = new RendererVO(idx, flag ? "Y" : "N");
}
}
]]>
</mx:Script>
<mx:DataGrid id="myGrid" dataProvider="{initDG}" width="450" height="150" editable="false">
<mx:columns>
<mx:DataGridColumn headerText="no" dataField="no" width="150"/>
<mx:DataGridColumn headerText="isChecked" dataField="isChecked" width="150"/>
<mx:DataGridColumn dataField="isChecked" headerText="itemRenderer">
<mx:itemRenderer>
<mx:Component>
<mx:CheckBox click="changeVO(event)">
<mx:Script>
<![CDATA[
[Bindable] private var rdVO:RendererVO2;
override public function set data(value:Object):void {
rdVO = RendererVO2(value);
if(value.isChecked == "Y") {
this.selected = true;
} else {
this.selected = false;
}
}
private function changeVO(event:Event):void {
trace(event.target.selected ? "Y" : "N");
var parentObj:Object = event.target.parentApplication;
parentObj.initDG[rdVO.no] = new RendererVO2(rdVO.no, event.target.selected ? "Y" : "N");
}
]]>
</mx:Script>
</mx:CheckBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
<mx:Button label="전체선택/해제" click="checkAll()"/>
< /mx:Application>

###파일명 RendererVO2.as
package {
public class RendererVO2 {
[Bindable] public var no:Number;
[Bindable] public var isChecked:String;
public function RendererVO2(p_no:Number, p_isChecked:String) {
this.no = p_no;
this.isChecked = p_isChecked;
}
}
Posted by 1010
반응형
Posted by 1010
54.iBATIS, MyBatis/iBatis2012. 4. 27. 17:15
반응형

이전에 살펴본 DynamicQuery부분에 사용한 옵션 외에 다양한 옵션이 제공 된다. 일반적으로 이런 옵션들을 이용할때 DAO에 쿼리가 박혀있을 경우 매우 복잡해진다. 따라서 스토어드 프로시저를 이용한다거나 하는 방식을 택하게 되는데, iBATIS에서 지원하는 옵션들을 살펴보자

  1. <!--property가 존재 하는지 검사(map의경우 property를 key로 검색실패) -->
  2. <isPropertyAvailable property=""></isPropertyAvailable>
  3. <!--property가 존재 하지 않는지 검사(map의경우 property를 key로 검색실패) -->
  4. <isNotPropertyAvailable property=""></isNotPropertyAvailable>
  5. <!--property가 null인지 검사 -->
  6. <isNotNull property=""></isNotNull>
  7. <!--property가 null이 아닌지 검사 -->
  8. <isNull property=""></isNull>
  9. <!-- property가 비어있는지 검사("".equals) 검사-->
  10. <isEmpty prepend=""></isEmpty>
  11. <!-- property가 비어있지 않은지 검사(!"".equals) 검사-->
  12. <isNotEmpty prepend=""></isNotEmpty>
  13. <!-- property가 비교값과 같은지 검사-->
  14. <isEqual property="" compareValue="" compareProperty=""></isEqual>
  15. <!-- property가 비교값과 같지 않은지 검사-->
  16. <isNotEqual property="" compareValue="" compareProperty=""></isNotEqual>
  17. <!-- property가 비교값보다 큰지 검사 -->
  18. <isGreaterThan property="" [compareValue="" || compareProperty=""]></isGreaterThan>
  19. <!-- property가 비교값보다 큰거나 같은지 검사 -->
  20. <isGreaterEqual property="" [compareValue="" || compareProperty=""]></isGreaterEqual>
  21. <!-- propety가 작은지 검사 -->
  22. <isLessThan property="" [compareValue="" || compareProperty=""]></isLessThan>
  23. <!-- propety가 작거나 같은지 검사 -->
  24. <isLessEqual property="" [compareValue="" || compareProperty=""]></isLessEqual>
  25. <!-- property를 반복하며 추가. 반복시 값의 사이에 conjunction정의 문자 삽입 -->
  26. <iterate property="" open="(" close=")" conjunction=","></iterate>

그냥 눈으로만 봐도 충분히 숙지할 수 있는 사항이므로 별도의 설명은 하지 않겠다. 조건에 property는 당연히 들어가는것이 원칙이다. 비교할 대상이나 검사할 대상이 없다면 뭐하러 이런 조건을 사용 하겠는가? 어렵지 않은 내용이지만 한가지 숙지해야 할 사항이 있다.

바로 이항연산자 부분에서 compareValue와 compareProperty인데 다른 부분은 property를 이용해 비교했다. 같은 property가 들어가는걸로 보아 compareProperty는 프로퍼티 중에서 비교하는 것을알수 있다.즉 '같이 넘어온 객체의 프로퍼티와 비교'하여 구문을 추가할지 선택하는것이다.

compareValue는 정적인 값이다. 예를들어 조건이 '성적이 100점 이하'일 경우 100은 정적인 값이다. 만약 이것을 compareProperty로 이용한다면 사용할때마다 '100'의 값을 셋팅해야할 것이다. 이럴때 compareValue를 이용하면 프로그램 코드에 별도로 관리할 필요가 없으므로 유용하게 사용할수 있다. 그럼 예제를 살펴보자.


boardManager.xml

  1. <typeAlias alias="boardbean" type="pupustory.ibatis.beans.BoardBean"/>
  2. <resultMap class="boardbean" id="boardbean">
  3. <result property="postId" column="post_Id"/>
  4. <result property="postTitle" column="post_Title"/>
  5. <result property="postWriter" column="post_Writer"/>
  6. <result property="postBody" column="post_Body"/>
  7. </resultMap>
  8. <parameterMap class="boardbean" id="boardbean">
  9. <parameter property="postId" />
  10. <parameter property="postTitle"/>
  11. <parameter property="postWriter"/>
  12. <parameter property="postBody"/>
  13. </parameterMap>
  14. <select id="select.board" resultMap="boardbean"
  15. parameterClass="boardbean" >
  16. SELECT
  17. A.POST_ID AS POST_ID
  18. ,A.POST_TITLE AS POST_TITLE
  19. ,A.POST_WRITER AS POST_WRITER
  20. ,B.POST_BODY AS POST_BODY
  21. FROM TB_MAIN_BOARD A, TB_SUB_BOARD B
  22. WHERE A.POST_ID = B.POST_ID
  23. <dynamic open="" close="">
  24. <isNull prepend=" AND " property="postId">
  25. 11=1
  26. </isNull>
  27. <isNotNull prepend=" AND " property="postId">
  28. a.post_id = #postId#
  29. </isNotNull>
  30. <isNotNull prepend=" AND " property="postTitle">
  31. post_title like '%' || #postTitle# || '%'
  32. </isNotNull>
  33. <isNotNull prepend=" AND " property="postWriter">
  34. post_Writer like '%' || #postWriter# || '%'
  35. </isNotNull>
  36. <isNotNull prepend=" AND " property="postBody">
  37. post_body like '%' || #postBody# || '%'
  38. </isNotNull>
  39. </dynamic>
  40. </select>
  41. <insert id="insert.main.board" parameterClass="boardbean">
  42. insert into tb_main_board
  43. values(#postId#,#postTitle#,#postWriter#)
  44. </insert>
  45. <insert id="insert.sub.board" parameterClass="boardbean">
  46. insert into tb_sub_board(post_id, post_body)
  47. values(#postId#,#postBody#)
  48. </insert>
  49. </sqlMap>


BoardBean.java

  1. package pupustory.ibatis.beans;
  2. public class BoardBean {
  3. String postId;
  4. String postTitle;
  5. String postWriter;
  6. String postBody;
  7. public String getPostBody() {
  8. return postBody;
  9. }
  10. public void setPostBody(String postBody) {
  11. this.postBody = postBody;
  12. }
  13. public String getPostId() {
  14. return postId;
  15. }
  16. public void setPostId(String postId) {
  17. this.postId = postId;
  18. }
  19. public String getPostTitle() {
  20. return postTitle;
  21. }
  22. public void setPostTitle(String postTItle) {
  23. this.postTitle = postTItle;
  24. }
  25. public String getPostWriter() {
  26. return postWriter;
  27. }
  28. public void setPostWriter(String postWriter) {
  29. this.postWriter = postWriter;
  30. }
  31. public String toString() {
  32. return "postId["+postId+"]"
  33. +"postTitle["+postTitle+"]"
  34. +"postWriter["+postWriter+"]"
  35. +"postBody["+postBody+"]";
  36. }
  37. }


BoardBiz.java

  1. package pupustory.ibatis.board;
  2. import pupustory.ibatis.manager.DBManager;
  3. import pupustory.ibatis.beans.BoardBean;
  4. import java.sql.SQLException;
  5. public class BoardBiz {
  6. DBManager manager = DBManager.getInstance();
  7. // 가상 데이터 삽입
  8. public void insertVirData() throws SQLException{
  9. BoardBean bean = null;
  10. final int MAX_BOARD_DATA = 10;
  11. manager.startTransaction();
  12. manager.startBatch();
  13. for (int i=0;i<MAX_BOARD_DATA;i++) {
  14. bean = new BoardBean();
  15. bean.setPostId(i+"");
  16. bean.setPostTitle("제목! "+i);
  17. bean.setPostWriter("pupustory"+i);
  18. bean.setPostBody("본문 히히히히 헤헤"+i);
  19. manager.getMapper().insert("insert.main.board", bean);
  20. manager.getMapper().insert("insert.sub.board", bean);
  21. }
  22. manager.executeBatch();
  23. manager.commitTransaction();
  24. }
  25. // 게시물 조회
  26. public java.util.List getPost(BoardBean bean)
  27. throws SQLException {
  28. return
  29. (java.util.List)manager.getMapper().queryForList("select.board",bean);
  30. }
  31. }

StartApp.java

  1. package pupustory.ibatis.board;
  2. import java.sql.SQLException;
  3. import pupustory.ibatis.beans.BoardBean;
  4. public class StartApp {
  5. public static void main(String ar[]) throws SQLException{
  6. BoardBiz biz = new BoardBiz();
  7. //biz.insertVirData();
  8. BoardBean bean = null;
  9. java.util.List list = biz.getPost(bean);
  10. for (int i=0;i<list.size();i++) {
  11. System.out.println(list.get(i).toString());
  12. }
  13. bean = new BoardBean();
  14. // id 3번 게시물 조회
  15. bean.setPostId("3");
  16. list = biz.getPost(bean);
  17. for (int i=0;i<list.size();i++) {
  18. System.out.println(list.get(i).toString());
  19. }
  20. // 본문에 '4'문자 포함한 게시물 조회
  21. bean = new BoardBean();
  22. //bean.setPostId("2");
  23. bean.setPostBody("4");
  24. list = biz.getPost(bean);
  25. for (int i=0;i<list.size();i++) {
  26. System.out.println(list.get(i).toString());
  27. }
  28. }
  29. }


조회조건에 들어올 값을 확인하고, null이 아닐경우 검색해서 출력한다. equal같은 검색조건을 추가하려 했지만.. 귀찮기도해서 --; 어차피 사용법은 동일하다. 그리고 dynamic부분의 prepend는 삭제했다. 이유는 이미 join을 하기위해 where를 호출했고, 뒤에 올 조건이 있을지 없을지 미지수다. 따라서 삭제 했다. 1=1은 게시 전에 몇가지 만지작 거리다 남은 코드이므로 무시해도 무관하다.

단항,이항 검색조건은 위와 같이 수행하면 되므로 어려울 것이 없다. 그렇다면 이번엔 이터레이터에 대해 알아볼 것이다. 이전에 설명 했지만 만약 사용자가 ' where board_id in (....) '와 같이 몇건이 들어올지 모르는 경우에 유용 하다.

이부분은 $$를 이용한 statment를 이용할 수도 있겠지만 이건 매우 위험하다. sql injection때문에 그렇다. 어플에서 .replace했다면 상관 없겠지만 그래도 프레임워크를 이용하니 .. 기능을 이용해 보도록 하자.

먼저 IN ( ...) 부분엔 정확히 얼마의 문자가 올지 모른다. 한가지 유추할 수 있는 것은 여기엔 배열이 적합한 것 이다. 새로운 예를 만드는 것 보다 위의 코드를 조금 변경해 작성하도록 하자. 먼저 빈즈에 POST_ID값이 저장될 배열 변수를 하나 추가한다.

  1. private String rePostId;
  2. public String getRePostId() {
  3. return rePostId;
  4. }
  5. public void setRePostId(String rePostId) {
  6. this.rePostId = rePostId;
  7. }
  8. public String toString() {//toString()는 값 확인을 위해 변경 함
  9. return "postId [" +rePostId+"]"
  10. +" postTitle [" +postTitle+"]"
  11. +" postWriter [" +postWriter+"]"
  12. +" postBody [" +postBody+"]"
  13. +" parentPostId [" +parentPostId+"]";
  14. }


이제 중요한 sqlmap부분이다.

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE sqlMap
  3. PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
  4. "http://ibatis.apache.org/dtd/sql-map-2.dtd">
  5. <sqlMap namespace="UserManager">
  6. <typeAlias alias="postreply" type="pupustory.ibatis.beans.PostReplyBean"/>
  7. <resultMap class="postreply" id="postreply.result" >
  8. <result property="rePostId" column="POST_ID" />
  9. <result property="postTitle" column="POST_TITLE" />
  10. <result property="postWriter" column="POST_WRITER" />
  11. <result property="postBody" column="POST_BODY" />
  12. <result property="parentPostId" column="PARENT_POST_ID" />
  13. </resultMap>
  14. <parameterMap class="postreply" id="postreply.param">
  15. <parameter property="postId" />
  16. <parameter property="postTitle"/>
  17. <parameter property="postWriter"/>
  18. <parameter property="postBody" />
  19. <parameter property="parentPostId"/>
  20. </parameterMap>
  21. <select id="select.dynamic.query" resultMap="postreply.result"
  22. parameterClass="postreply" >
  23. SELECT * FROM TB_QNA_BOARD
  24. <dynamic prepend="WHERE">
  25. <iterate property="postId"
  26. conjunction="," open="post_id IN (" close=")" >
  27. #postId[]#
  28. </iterate>
  29. </dynamic>
  30. </select>
  31. </sqlMap>


반복 부분을 iterator를 사용했다. 실행코드를 살펴보자.

  1. package pupustory.ibatis.dynamicquery;
  2. import pupustory.ibatis.beans.PostReplyBean;
  3. public class StartApp {
  4. public static void main(String ar[]) throws java.sql.SQLException {
  5. PostReplyBean bean = new PostReplyBean();
  6. DynamicQueryBiz biz = new DynamicQueryBiz();
  7. String[] postIds = {"1","2","4","5","7","9"};
  8. bean.setPostId(postIds);
  9. java.util.List list = biz.getPostBoard(bean);
  10. if (list.get(0) instanceof PostReplyBean) {
  11. System.out.println("true");
  12. }
  13. for (int i=0;i<list.size();i++) {
  14. bean = (PostReplyBean)list.get(i);
  15. System.out.println(bean.toString());
  16. }
  17. }
  18. }

어려운 구문은 없다. xml에서 open부분에 in ( 를 추가 했고, 배열마다 구분문자는 ','로 지정했다. 완료 후 ) 로 닫으니

SELECT * FROM TB_QNA_BOARD WHERE POST_ID IN ('1','2','4','5','7','9');

와 같은 sql 구문이 생성 된다. resultMap에선 실제 우리가 가져와야 할 빈의 변수와 맵핑하면 된다.

[출처] http://pupustory.tistory.com/184

Posted by 1010
54.iBATIS, MyBatis/iBatis2012. 4. 27. 00:05
반응형

iBatis를 사용하다 보니 또하나의 문제에 봉착했다.. LIKE 검색의 %기호를 인식하지 못하는 것이었다.


구글신에게 검색해 보고 다음과 같은 해결책을 얻을 수 있었다.

MySQL :
SELECT * FROM tbl_name WHERE column_name LIKE "%$username$%"

ORACLE :
SELECT * FROM tbl_name WHERE column_name LIKE '%' || #username# || '%'

SYBASE/SQL SERVER
SELECT * from tbl_name WHERE column_name LIKE '%' + #username# + '%'



여기서 변수명을 #로 둘러싸는 것과 $로 둘러싸는것의 차이점을 알 필요가 있다.
#의 경우에는 Prepare Statement로 등록이 된다. 디버그를 찍어봐도 ?로 치환된 이후 값이 대입된다.
하지만 $의 경우 바로 값이 치환된다. 특정 변수가 바로 DB에 입력되므로 보안에 좀더 신경을 써야 할것으로 생각된다.



3.9. Dynamic SQL

ADO에서 작업을 수행할때 발생되는 문제는 동적 SQL 이었다. 이것은 보통 SQL 문장과 함께 작업할때 파라미터의 값을 변경하는 작업으로 어려울때 이용을 하게 된다. 일반적인 방법은 if-else를 이용하거나, 끔찍한 스트링 조합으로 이를 해결하고 있다. 바라던 결과는 종종 각 예에 따른 쿼리를 작성하는 것이다. iBATIS DataMapper API는 어떠한 매핑되는 문장의 엘리먼트에도 적용할 수 있도록 좀더 좋은 코드를 만들 수 있도록 지원해준다. 간단한 예를 보면 다음과 같다.

Example 3.56. A simple dynamic select sttatement, with two possible outcomes

< select id="dynamicGetAccountList" cacheModel="account-cache" parameterClass="Account"
resultMap="account-result" >
select * from ACCOUNT
<isGreaterThan prepend="and" property="Id" compareValue="0">
where ACC_ID = #Id#
</isGreaterThan>
order by ACC_LAST_NAME
< /select>

상단에 제시된 예제는 2개의 가능한 문장을 생성해낼 수 있으며, 이 기준은 Id 프로퍼티에 들어갈 파라미터 객체에 달려 있다. 만약에 Id 파라미터가 0보다 큰 경우 문장은 다음 쿼리를 만들어 낸다.

select * from ACCOUNT where ACC_ID = ?

만약 파라미터가 0보다 작거나 인경우에는 스테이트 먼트는 다음과 같은 쿼리를 만든다.

select * from ACCOUNT


복잡한 상황에 부딛히지 않을경우 언뜻 보기에는 유용하지 않을 수있다. 예를 들어 다음과 같은 복잡한 상황이 될경우는 달라진다.

Example 3.57. A complex dynamic select statement, with 16 possible outcomes

< select id="dynamicGetAccountList" parameterClass="Account" resultMap="account-result" >
select * from ACCOUNT
<dynamic prepend="WHERE">
<isNotNull prepend="AND" property="FirstName">
( ACC_FIRST_NAME = #FirstName#
<isNotNull prepend="OR" property="LastName">
ACC_LAST_NAME = #LastName#
</isNotNull>
)
</isNotNull>
<isNotNull prepend="AND" property="EmailAddress">
ACC_EMAIL like #EmailAddress#
</isNotNull>
<isGreaterThan prepend="AND" property="Id" compareValue="0">
ACC_ID = #Id#
</isGreaterThan>
</dynamic>
order by ACC_LAST_NAME
< /select>

이러한 상황에서는 1개의 서로다른 쿼리가 만들어 진다. if-else 구문과 스트링 조합으로 만든다면 아마도 매우 혼란하고, 수백 라인의 코드가 필요할 수있을 것이다.

dynamic 문장은 가능하면 간단한 컨디션 태그를 SQL에 넣어야 한다. 예를 들면 다음과 같다.

Example 3.58. Creating a dynamic statement with conditional tags

< statement id="someName" parameterClass="Account" resultMap="account-result" >
select * from ACCOUNT
<dynamic prepend="where">
<isGreaterThan prepend="and" property="id" compareValue="0">
ACC_ID = #id#
</isGreaterThan>
<isNotNull prepend="and" property="lastName">
ACC_LAST_NAME = #lastName#
</isNotNull>
</dynamic>
order by ACC_LAST_NAME
< /statement>

상기 구문에서 <dynamic>엘리먼트로 쌓여있는 SQL의 영역이 동적 영역이다. dynamic 엘리먼트는 옵션이고, prepend("WHERE")를 이용하여 조건 문장을 포함하지 않고서도 조건절을 적용할 수 있도록 해준다. 스테이트먼트 섹션은 아래에서 말하는것과 같이 몇개의 컨디션 엘리먼트를 포함하고 있다. 모든 컨디션 엘리먼트쿼리에 파라미터 객체를 전달한 상태를 기본으로 처리가 된다. prepend 속성은 코드 부분으로 이것은 필요한 경우 상위 엘리먼트의 prepend를 상속 받는다. 상기 예에세는 "where" prepend를 첫번째 조건이 true인경우 적용이 된다. 이것은 SQL 문장이 정당하게 만들어 졌는지 보장하는데 필요한 요소이다. 예를 들어 첫번째 상황이 true인상황이고, AND가 필요없다고 한다면 사실 스테이트먼트는 깨질 것이다. 다음 섹션에서 엘리먼트의 다양한 종류에 대해서 설명하고, Binary Conditionals와 Unary Conditionals 그리고 반복에 대해서 다룰 것이다.

3.9.1. Binary Conditional Elements

이항 조건 엘리먼트는 속성 값과 정적값을 비고하거나 다른 프로퍼티 값과 비교를 수행한다. 만약 결과가 true인경우 바디 컨텐츠는 SQL 쿼리문에 포함된다.

3.9.1.1. Binary Conditional Attributes:

prepend – 구문이 SQL 의 부분으로 붙어서 사용될 것인지 결정한다. (옵션)
property – 비교할 대상 프로퍼티 (필요)
compareProperty – 비교할 다른 프로퍼티(필수 혹은 비교할 값)
compareValue – 비교할 값 (필수 혹은 compareProperty)

Table 3.7. Binary conditional attributes

Element Description
<isEqual> 두 프로퍼티의 비교에서 프로퍼티의 값이 다른 프로퍼티와 동일한지 검사
<isEqual prepend="AND" property="status" compareValue="Y"> MARRIED = ‘TRUE'
< /isEqual>
<isNotEqual> 하나의 프로퍼티가 다른 프로퍼티와 다른지 검사<isNotEqual prepend="AND" property="status" compareValue="N"> MARRIED = ‘FALSE'
< /isNotEqual>
<isGreaterThan> 하나의 프로퍼티가 다른 프로퍼티보다 큰지 검사
<isGreaterThan prepend="AND" property="age" compareValue="18"> ADOLESCENT = ‘FALSE'
< /isGreaterThan>
<isGreaterEqual> 하나의 프로퍼티가 다른 프로퍼티값보다 크거나 같은지 검사한다.<isGreaterEqual prepend="AND" property="shoeSize" compareValue="12"> BIGFOOT = ‘TRUE'
< /isGreaterEqual>
<isLessEqual> 프로퍼티가 다른 프로퍼티보다 작거나 같은지 검사한다.<isLessEqual prepend="AND" property="age" compareValue="18"> ADOLESCENT = ‘TRUE'
< /isLessEqual>


 

3.9.2. Unary Conditional Elements

단항 조건 엘리먼트는 특정 상황에 대해서 프로퍼티의 상태를 검사한다.

3.9.2.1. Unary Conditional Attributes:

prepend – 적용하고자 하는 문장 (옵션)
property – 체크된 프로퍼티 (필수)

Table 3.8. Unary conditional attributes

Element Description
<isPropertyAvailable> 프로퍼티가 사용가능한 상태인지 체크한다.<isPropertyAvailable property="id" >
ACCOUNT_ID=#id#
< /isPropertyAvailable>
<isNotPropertyAvailable> 프로퍼티가 사용가능하지 않는지 검사한다.<isNotPropertyAvailable property="age" >
STATUS='New'
< /isNotEmpty>
<isNull> 프로퍼티가 널인지 검사한다.
<isNull prepend="AND" property="order.id" >
ACCOUNT.ACCOUNT_ID = ORDER.ACCOUNT_ID(+)
< /isNotEmpty>
<isNotNull> 프로퍼티가 널이 아닌지 검사한다.
<isNotNull prepend="AND" property="order.id" >
ORDER.ORDER_ID = #order.id#
< /isNotEmpty>
<isEmpty> 컬렉션 벨류, 스트링이 널이거나 혹은 비어 잇는지 ("" 혹은 size() < 1)인지 검사한다.<isEmpty property="firstName" >
LIMIT 0, 20
< /isNotEmpty>
<isNotEmpty> 컬렉션 밸류, 스트링이 널이 아닌지, 혹은 비어있지 않은지 검사한다.
<isNotEmpty prepend="AND" property="firstName" >
FIRST_NAME LIKE '%$FirstName$%'
< /isNotEmpty>


 

3.9.3. Parameter Present Elements

이 엘리먼트는 파라미터 객체의 존재에 대해서 체크를 수행한다.

3.9.3.1. Parameter Present Attributes:

prepend – 적용할 문장 구문 (옵션)

Table 3.9. Testing to see if a parameter is present

Element Description
<isParameterPresent> 파라미터 객체가 현재 값이 존재하는지 (널이 아닌지)검사한다.<isParameterPresent prepend="AND">
EMPLOYEE_TYPE = #empType#
< /isParameterPresent>
<isNotParameterPresent> 파라미터 객체가 현재 값이 아닌지 (널인지) 검사한다.<isNotParameterPresent prepend="AND">
EMPLOYEE_TYPE = ‘DEFAULT'
< /isNotParameterPresent>


 

3.9.4. Iterate Element

이 태그는 컬렉션을 반복하고, 리스트에서 각 아이템의 내용을 반복한다.

3.9.4.1. Iterate Attributes:

prepend – 사용할 구문(옵션)
property – 반복할 리스트 객체 (필수)
open – 반복에서 전체 블록을 열어줄때 시작할 단어 보통 [, ( 이 이용된다. (옵션)
close – 블록 반복의 끝에 닫을때 사용할 단어 보통 ], ) 이 이용된다.(옵션)
conjunction – 반복할 단어 사이에 연결자 AND, OR (옵션)


 

Table 3.10. Creating a list of conditional clauses

Element Description
<iterate> 리스트 반복 예제
<iterate prepend="AND" property="UserNameList"
open="(" close=")" conjunction="OR">
username=#UserNameList[]#
< /iterate>Note: [] 을 리스트 의 시작과 끝을 나타낼때 매우 중요한 값이다. 이 브라켓은 리스트에서 단순히 스트링 값을 담고 있다고 판단하고, 값을 출력하게 된다.


3.9.5. Simple Dynamic SQL Elements

상단에 설명한 전체 동적 매핑된 구문의 강력함에도 불구하고, 가끔 단순하고, 작은 내용을 처리해야할 때가 있다. 여기 예에서는 SQL 스테이트문에는 단순한 동적 SQL 엘리먼트를 포함할 수 있으며 이것은 order by 문장에서 동적 구문을 구현하도록 하고 있다. 이것은 인파인 파라미터와 매우 닮은 형태를 가지고 있다. 그러나 약간의 차이점이 있자. 다음 예를 보자.

Example 3.59. A dynamic element that changes the collating order

< statement id="getProduct" resultMap="get-product-result">
select * from PRODUCT order by $preferredOrder$
< /statement>

상단의 예에서 preferredOrder 동적 엘리먼트는 파라미터 객체로 넘어온 preferredOrder의 값으로 대체된다. 차이점은 SQL 문장을 근본적으로 바꾼다는 것이고, 단순하게 파라미터 값을 세팅하는 것보다 더 심각할 수 있다. 동적 엘리먼트를 잘못 만들게 되면 보안, 성능, 안정성의 문제를 야기 시킨다. 그러므로 나머지 부분의 체크를 수행하기 위해서 적당한 다이나믹 엘리먼트를 이용해야할 것이다. 또한 디자인에서 명심해야할 것은 잠재적으로 데이터베이스 스펙이 비즈니스 객체 모델을 침범할 수 있다는것을 알아야 한다.
For example, you may not want a column name intended for an order by clause to end up as a property in your business object, or as a field value on your server page.

단순한 동적 엘리먼트는 <statements>를 추가하고, 변화가 필요한 부분을 직접 수정하면 된다.

Example 3.60. A dynamic element that changes the comparison operator

< statement id="getProduct" resultMap="get-product-result">
SELECT * FROM PRODUCT
<dynamic prepend="WHERE">
<isNotEmpty property="Description">
PRD_DESCRIPTION $operator$ #Description#
</isNotEmpty>
</dynamic>
< /statement>

상단 예제는 $operator$토큰을 전달 엘리먼트로 교체하는 예제이다. 만약 검색이 LIKE 검색을 수행하는 경우 %dog%로 값이 들어왔다면 SQL 문장은 다음과 같은 구문을 만들어 낸다.

SELECT * FROM PRODUCT WHERE PRD_DESCRIPTION LIKE ‘%dog%'
Posted by 1010
98..Etc/Hibernate2012. 4. 10. 10:25
반응형

머리말
1. Feedback
1. Tutorial
1.1. 파트 1 - 첫 번째 Hibernate 어플리케이션
1.1.1. Setup
1.1.2. 첫 번째 클래스
1.1.3. The mapping file
1.1.4. Hibernate 구성
1.1.5. Building with Maven
1.1.6. 시작과 helper들
1.1.7. 객체 로딩과 객체 저장
1.2. 파트 2 - 연관들을 매핑하기
1.2.1. Person 클래스 매핑하기
1.2.2. 단방향 Set-기반의 연관
1.2.3. 연관들에 작업하기
1.2.4. 값들을 가진 콜렉션
1.2.5. Bi-directional associations
1.2.6. 양방향 링크들에 작업하기
1.3. 파트 3 - EventManager 웹 어플리케이션
1.3.1. 기본 서블릿 작성하기
1.3.2. 프로세싱과 렌더링
1.3.3. 배치하기 그리고 테스트하기
1.4. 요약
2. 아키텍처
2.1. 개요
2.2. 인스턴스 상태들
2.3. JMX 통합
2.4. JCA 지원
2.5. Contextual sessions
3. 구성
3.1. 프로그램 상의 구성
3.2. SessionFactory 얻기
3.3. JDBC 커넥션들
3.4. 선택적인 구성 프로퍼티들
3.4.1. SQL Dialects
3.4.2. Outer Join Fetching
3.4.3. Binary Streams
3.4.4. Second-level 캐시와 query 캐시
3.4.5. Query Language 치환
3.4.6. Hibernate 통계
3.5. 로깅
3.6. NamingStrategy 구현하기
3.7. XML 구성 파일
3.8. J2EE 어플리케이션 서버 통합
3.8.1. 트랜잭션 방도 구성
3.8.2. JNDI-bound SessionFactory
3.8.3. Current Session context management with JTA
3.8.4. JMX 배치
4. 영속 클래스들
4.1. 간단한 POJO 예제
4.1.1. 아규먼트 없는 생성자를 구현하라
4.1.2. identifier 프로퍼티를 제공하라(옵션)
4.1.3. final이 아닌 클래스들을 선호하라(옵션)
4.1.4. 영속 필드들을 위한 accessor들과 mutator들을 선언하라(옵션)
4.2. 상속 구현하기
4.3. equals()와 hashCode() 구현하기
4.4. 동적인 모형들
4.5. Tuplizer들
4.6. EntityNameResolvers
5. 기본 O/R 매핑
5.1. 매핑 선언
5.1.1. Doctype
5.1.2. Hibernate-mapping
5.1.3. Class
5.1.4. id
5.1.5. NOT TRANSLATED!Enhanced identifier generators
5.1.6. NOT TRANSLATED! Identifier generator optimization
5.1.7. composite-id
5.1.8. Discriminator
5.1.9. Version (optional)
5.1.10. Timestamp (optional)
5.1.11. Property
5.1.12. Many-to-one
5.1.13. One-to-one
5.1.14. Natural-id
5.1.15. Component and dynamic-component
5.1.16. Properties
5.1.17. Subclass
5.1.18. Joined-subclass
5.1.19. Union-subclass
5.1.20. Join
5.1.21. Key
5.1.22. Column and formula elements
5.1.23. Import
5.1.24. Any
5.2. Hibernate types
5.2.1. 엔티티들과 값들
5.2.2. 기본 value 타입들
5.2.3. 맞춤형 value 타입들
5.3. 하나의 클래스를 한 번 이상 매핑하기
5.4. SQL 인용부호 표시된 식별자들
5.5. Metadata 대안들
5.5.1. XDoclet 마크업 사용하기
5.5.2. JDK 5.0 Annotations 사용하기
5.6. Generated properties
5.7. Auxiliary database objects
6. Collection mapping
6.1. 영속 콜렉션들
6.2. 콜렉션 매핑들
6.2.1. 콜렉션 foreign 키들
6.2.2. 콜렉션 요소들
6.2.3. 인덱싱 된 콜렉션들
6.2.4. 값들을 가진 콜렉션들과 many-to-many 연관들
6.2.5. One-to-many 연관들
6.3. 개선된 콜렉션 매핑들
6.3.1. Sorted 콜렉션들
6.3.2. 양방향 연관들
6.3.3. 인덱싱된 콜렉션들을 가진 양방향 연관들
6.3.4. Ternary associations(세겹 연관들)
6.3.5. <idbag> 사용하기
6.4. 콜렉션 예제들
7. 연관 매핑들
7.1. 개요
7.2. 단방향 연관들
7.2.1. Many-to-one
7.2.2. One-to-one
7.2.3. One-to-many
7.3. join 테이블들에 대한 단방향 연관들
7.3.1. One-to-many
7.3.2. Many-to-one
7.3.3. One-to-one
7.3.4. Many-to-many
7.4. 양방향 연관들
7.4.1. one-to-many / many-to-one
7.4.2. One-to-one
7.5. join 테이블들에 대한 양방향 연관들
7.5.1. one-to-many / many-to-one
7.5.2. one to one
7.5.3. Many-to-many
7.6. 보다 복잡한 연관 매핑들
8. Component 매핑
8.1. 종속 객체들
8.2. 종속 객체들을 가진 콜렉션들
8.3. Map 인덱스들로서 컴포넌트들
8.4. composite 식별자들로서 컴포넌트들
8.5. 동적인 컴포넌트들
9. Inheritance mapping
9.1. The three strategies
9.1.1. Table per class hierarchy
9.1.2. Table per subclass
9.1.3. Table per subclass: using a discriminator
9.1.4. table per class hierarchy와 table per subclass를 혼합하기
9.1.5. Table per concrete class
9.1.6. Table per concrete class using implicit polymorphism
9.1.7. 함축적인 다형성을 다른 상속 매핑들과 혼합하기
9.2. 제약들
10. 객체들로 작업하기
10.1. Hibernate 객체 상태들
10.2. 객체들을 영속화 시키기
10.3. 객체를 로드시키기
10.4. 질의하기
10.4.1. 질의들을 실행하기
10.4.2. 콜렉션들을 필터링 하기
10.4.3. Criteria 질의들
10.4.4. native SQL에서 질의들
10.5. 영속 객체들을 변경하기
10.6. detached 객체들을 변경시키기
10.7. 자동적인 상태 검출
10.8. 영속 객체들을 삭제하기
10.9. 두 개의 다른 데이터저장소들 사이에 객체들을 복제하기
10.10. Session을 flush 시키기
10.11. Transitive persistence(전이 영속)
10.12. 메타데이터 사용하기
11. Transactions and Concurrency
11.1. 세션 영역과 트랜잭션 영역
11.1.1. 작업 단위
11.1.2. 장기간의 대화
11.1.3. 객체 identity 고려하기
11.1.4. 공통된 쟁점들
11.2. 데이터베이스 트랜잭션 경계 설정
11.2.1. 관리되지 않는 환경
11.2.2. JTA 사용하기
11.2.3. 예외상황 처리
11.2.4. 트랜잭션 타임아웃
11.3. Optimistic 동시성 제어
11.3.1. 어플리케이션 버전 체킹
11.3.2. 확장된 세션과 자동적인 버전화
11.3.3. Detached 객체들과 자동적인 버전화
11.3.4. 자동적인 버전화를 맞춤화 시키기
11.4. Pessimistic locking
11.5. Connection release modes
12. 인터셉터들과 이벤트들
12.1. 인터셉터들
12.2. 이벤트 시스템
12.3. Hibernate 선언적인 보안
13. Batch 처리
13.1. Batch inserts
13.2. Batch updates
13.3. StatelessSession 인터페이스
13.4. DML-스타일 연산들
14. HQL: 하이버네이트 질의 언어(Hibernate Query Language)
14.1. 대소문자 구분
14.2. from 절
14.3. 연관들과 조인들
14.4. join 구문의 형식들
14.5. Referring to identifier property
14.6. select 절
14.7. 집계 함수들
14.8. Polymorphic(다형성) 질의들
14.9. where 절
14.10. 표현식들
14.11. order by 절
14.12. group by 절
14.13. 서브질의들
14.14. HQL 예제들
14.15. 대량 update와 delete
14.16. 팁들 & 트릭들
14.17. 컴포넌트들
14.18. Row value constructor 구문
15. Criteria 질의들
15.1. Criteria 인스턴스 생성하기
15.2. 결과 셋 제한하기
15.3. 결과들을 순서지우기(ordering)
15.4. 연관들
15.5. 동적인 연관 페칭
15.6. 예제 질의들
15.7. Projections, aggregation 그리고 grouping
15.8. Detached 질의들과 서브질의들
15.9. natural 식별자에 의한 질의들
16. Native SQL
16.1. SQLQuery 사용하기
16.1.1. 스칼라 질의들
16.1.2. Entity 질의들
16.1.3. 연관들과 콜렉션들을 처리하기
16.1.4. 여러 개의 엔티티들을 반환하기
16.1.5. non-managed 엔티티들을 반환하기
16.1.6. 상속 처리하기
16.1.7. 파라미터들
16.2. 명명된 SQL 질의들
16.2.1. 명시적으로 column/alias 이름들을 지정하는데 return-property 사용하기
16.2.2. 질의를 위한 내장 프로시저 사용하기
16.3. create, update 그리고 delete를 위한 맞춤형 SQL
16.4. 로딩을 위한 맞춤형 SQL
17. 데이터 필터링하기
17.1. Hibernate 필터들
18. XML 매핑
18.1. XML 데이터로 작업하기
18.1.1. XML과 클래스 매핑을 함께 지정하기
18.1.2. XML 매핑만을 지정하기
18.2. XML 매핑 메타데이터
18.3. XML 데이터 처리하기
19. 퍼포먼스 개선하기
19.1. 페칭 방도들
19.1.1. lazy 연관들로 작업하기
19.1.2. 페치 방도들을 튜닝하기
19.1.3. Single-ended 연관 프락시
19.1.4. 콜렉션들과 프락시들을 초기화 시키기
19.1.5. batch 페칭 사용하기
19.1.6. subselect 페칭 사용하기
19.1.7. lazy 프로퍼티 페칭 사용하기
19.2. 두번째 레벨 캐시
19.2.1. Cache 매핑들
19.2.2. 방도: 읽기 전용
19.2.3. 방도: 읽기/쓰기
19.2.4. 방도: 엄격하지 않은 읽기/쓰기
19.2.5. 방도: transactional
19.2.6. Cache-provider/concurrency-strategy compatibility
19.3. 캐시들을 관리하기
19.4. 질의 캐시
19.5. 콜렉션 퍼포먼스 이해하기
19.5.1. 분류
19.5.2. List, map, idbag, set들은 update에 가장 효율적인 콜렉션들이다
19.5.3. Bag들과 list들은 가장 효율적인 inverse 콜렉션들이다
19.5.4. 원 샷 delete
19.6. 퍼포먼스 모니터링하기
19.6.1. SessionFactory 모니터링 하기
19.6.2. Metrics
20. 도구셋 안내
20.1. 자동적인 스키마 생성
20.1.1. 스키마 맞춤화 시키기
20.1.2. 도구 실행하기
20.1.3. 프로퍼티들
20.1.4. Ant 사용하기
20.1.5. 점증하는 스키마 업데이트들
20.1.6. 점증하는 스키마 업데이트들에 Ant 사용하기
20.1.7. 스키마 유효성 검사
20.1.8. 스키마 유효성 검사를 위해 Ant 사용하기
21. 예제: 부모/자식
21.1. 콜렉션들에 관한 노트
21.2. 양방향 one-to-many
21.3. 케스케이딩 생명주기
21.4. 케스케이드들과 unsaved-value
21.5. 결론
22. 예제: Weblog 어플리케이션
22.1. 영속 클래스들
22.2. Hibernate 매핑들
22.3. Hibernate 코드
23. 예제: 여러 가지 매핑들
23.1. Employer/Employee
23.2. Author/Work
23.3. Customer/Order/Product
23.4. 기타 예제 매핑들
23.4.1. "형식화된(Typed)" one-to-one 연관
23.4.2. Composite 키 예제
23.4.3. 공유된 합성 키 속성을 가진 Many-to-many
23.4.4. 내용 기반 판별
23.4.5. 대체 키들에 대한 연관들
24. 최상의 실전 경험들
25. Database Portability Considerations
25.1. Portability Basics
25.2. Dialect
25.3. Dialect resolution
25.4. Identifier generation
25.5. Database functions
25.6. Type mappings
References

Working with object-oriented software and a relational database can be cumbersome and time consuming in today's enterprise environments. Hibernate is an Object/Relational Mapping tool for Java environments. The term Object/Relational Mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. It can also significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database, it is most useful with object-oriented domain models and business logic in the Java-based middle-tier. However, Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular representation to a graph of objects.

만일 당신이 Hibernate와 Object/Relational 매핑 또는 심지어 자바에 초심자라면, 다음 단계들을 따르기 바란다:

  1. 더 많은 단계적인 사용 설명서들을 가진 더 긴 튜토리얼은 1장. Tutorial 을 읽어라. 튜토리얼을 위한 소스 코드는doc/reference/tutorial/ 디렉토리에 포함되어 있다.

  2. Hibernate가 사용될 수 있는 환경을 이해려면 2장. 아키텍처 를 읽어라.

  3. View the eg/ directory in the Hibernate distribution. It contains a simple standalone application. Copy your JDBC driver to the lib/ directory and edit etc/hibernate.properties, specifying correct values for your database. From a command prompt in the distribution directory, type ant eg (using Ant), or under Windows, type build eg.

  4. Use this reference documentation as your primary source of information. Consider reading [JPwH] if you need more help with application design, or if you prefer a step-by-step tutorial. Also visithttp://caveatemptor.hibernate.org and download the example application from [JPwH].

  5. FAQ들은 Hibernate 웹 사이트 상에 답변되어 있다.

  6. Links to third party demos, examples, and tutorials are maintained on the Hibernate website.

  7. Hibernate 웹사이트 상의 공동체 영역은 설계 패턴과 다양한 통합 솔루션들(Tomcat, JBoss AS, Struts, EJB 등.)에 관한 좋은 리소스이다.

If you have questions, use the user forum linked on the Hibernate website. We also provide a JIRA issue tracking system for bug reports and feature requests. If you are interested in the development of Hibernate, join the developer mailing list. If you are interested in translating this documentation into your language, contact us on the developer mailing list.

Hibernate를 위한 상용 개발 지원, 제품 지원, 그리고 교육은 JBoss Inc를 통해 이용 가능하다 (http://www.hibernate.org/SupportTraining/를 보라). Hibernate는 JBoss Professional Open Source product 프로젝트이고 제품들에 대한 JBoss Enterprise Middleware System (JEMS) suite의 중대한 컴포넌트이다.

Use Hibernate JIRA to report errors or request enhacements to this documentation.

Intended for new users, this chapter provides an step-by-step introduction to Hibernate, starting with a simple application using an in-memory database. The tutorial is based on an earlier tutorial developed by Michael Gloegl. All code is contained in the tutorials/web directory of the project source.

중요

This tutorial expects the user have knowledge of both Java and SQL. If you have a limited knowledge of JAVA or SQL, it is advised that you start with a good introduction to that technology prior to attempting to learn Hibernate.

참고

The distribution contains another example application under the tutorial/eg project source directory.

For this example, we will set up a small database application that can store events we want to attend and information about the host(s) of these events.

참고

Although you can use whatever database you feel comfortable using, we will use HSQLDB(an in-memory, Java database) to avoid describing installation/setup of any particular database servers.

The first thing we need to do is to set up the development environment. We will be using the "standard layout" advocated by alot of build tools such as Maven. Maven, in particular, has a good resource describing this layout. As this tutorial is to be a web application, we will be creating and making use ofsrc/main/javasrc/main/resources and src/main/webapp directories.

We will be using Maven in this tutorial, taking advantage of its transitive dependency management capabilities as well as the ability of many IDEs to automatically set up a project for us based on the maven descriptor.

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.hibernate.tutorials</groupId>
    <artifactId>hibernate-tutorial</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>First Hibernate Tutorial</name>

    <build>
         <!-- we dont want the version to be part of the generated war file name -->
         <finalName>${artifactId}</finalName>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <!-- Because this is a web app, we also have a dependency on the servlet api. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </dependency>

        <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>

        <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
        </dependency>
    </dependencies>

</project>

작은 정보

It is not a requirement to use Maven. If you wish to use something else to build this tutoial (such as Ant), the layout will remain the same. The only change is that you will need to manually account for all the needed dependencies. If you use something like Ivy providing transitive dependency management you would still use the dependencies mentioned below. Otherwise, you'd need to grab all dependencies, both explicit and transitive, and add them to the project's classpath. If working from the Hibernate distribution bundle, this would mean hibernate3.jar, all artifacts in the lib/required directory and all files from either the lib/bytecode/cglib or lib/bytecode/javassist directory; additionally you will need both the servlet-api jar and one of the slf4j logging backends.

Save this file as pom.xml in the project root directory.

Next, we create a class that represents the event we want to store in the database; it is a simple JavaBean class with some properties:

package org.hibernate.tutorial.domain;

import java.util.Date;

public class Event {
    private Long id;

    private String title;
    private Date date;

    public Event() {}

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

This class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields. Although this is the recommended design, it is not required. Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring.

The id property holds a unique identifier value for a particular event. All persistent entity classes (there are less important dependent classes as well) will need such an identifier property if we want to use the full feature set of Hibernate. In fact, most applications, especially web applications, need to distinguish objects by identifier, so you should consider this a feature rather than a limitation. However, we usually do not manipulate the identity of an object, hence the setter method should be private. Only Hibernate will assign identifiers when an object is saved. Hibernate can access public, private, and protected accessor methods, as well as public, private and protected fields directly. The choice is up to you and you can match it to fit your application design.

The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection. The constructor can be private, however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.

Save this file to the src/main/java/org/hibernate/tutorial/domain directory.

Hibernate는 영속 크래스들에 대한 객체들을 로드시키고 저장시키는 방법을 알 필요가 있다. 이곳은 Hibernate 매핑 파일이 역할을 행하는 곳이다. 매핑 파일은 Hibernate가 접근해야 하는 데이터베이스 내의 테이블이 무엇인지, 그리고 그것이 사용해야 하는 그 테이블 내의 컬럼들이 무엇인지를 Hibernate에게 알려준다.

매핑 파일의 기본 구조는 다음과 같다:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.hibernate.tutorial.domain">
[...]
</hibernate-mapping>

Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elements and attributes in your editor or IDE. Opening up the DTD file in your text editor is the easiest way to get an overview of all elements and attributes, and to view the defaults, as well as some comments. Hibernate will not load the DTD file from the web, but first look it up from the classpath of the application. The DTD file is included in hibernate-core.jar (it is also included in the hibernate3.jar, if using the distribution bundle).

Between the two hibernate-mapping tags, include a class element. All persistent entity classes (again, there might be dependent classes later on, which are not first-class entities) need a mapping to a table in the SQL database:

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

    <class name="Event" table="EVENTS">

    </class>

</hibernate-mapping>

So far we have told Hibernate how to persist and load object of class Event to the table EVENTS. Each instance is now represented by a row in that table. Now we can continue by mapping the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column:

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

    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
    </class>

</hibernate-mapping>

The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the EVENTS table holds the primary key value.

The nested generator element specifies the identifier generation strategy (aka how are identifier values generated?). In this case we choose native, which offers a level of portability depending on the configured database dialect. Hibernate supports database generated, globally unique, as well as application assigned, identifiers. Identifier value generation is also one of Hibernate's many extension points and you can plugin in your own strategy.

Lastly, we need to tell Hibernate about the remaining entity class properties. By default, no properties of the class are considered persistent:

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

    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>
    </class>

</hibernate-mapping>

Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use. In this case, Hibernate will search for getDate()setDate()getTitle() and setTitle()methods.

참고

Why does the date property mapping include the column attribute, but the title does not? Without the column attribute, Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name.

The title mapping also lacks a type attribute. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, converters which can translate from Java to SQL data types and vice versa. Again, Hibernate will try to determine the correct conversion and mapping type itself if the type attribute is not present in the mapping. In some cases this automatic detection using Reflection on the Java class might not have the default you expect or need. This is the case with the date property. Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL datetimestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter.

작은 정보

Hibernate makes this mapping type determination using reflection when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use.

Save this mapping file as src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml.

At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate. First let's set up HSQLDB to run in "server mode"

We will utilize the Maven exec plugin to launch the HSQLDB server by running:mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"You will see it start up and bind to a TCP/IP socket; this is where our application will connect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB, delete all files in thetarget/data directory, and start HSQLDB again.

Hibernate will be connecting to the database on behalf of your application, so it needs to know how to obtain connections. For this tutorial we will be using a standalone connection pool (as opposed to ajavax.sql.DataSource). Hibernate comes with support for two third-party open source JDBC connection pools: c3p0 and proxool. However, we will be using the Hibernate built-in connection pool for this tutorial.

경고

The built-in Hibernate connection pool is in no way intended for production use. It lacks several features found on any decent connection pool.

For Hibernate's configuration, we can use a simple hibernate.properties file, a more sophisticatedhibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

참고

Notice that this configuration file specifies a different DTD

You configure Hibernate's SessionFactory. SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier startup you should use several <session-factory>configurations in several configuration files.

The first four property elements contain the necessary configuration for the JDBC connection. The dialectproperty element specifies the particular SQL variant Hibernate generates.

작은 정보

In most cases, Hibernate is able to properly determine which dialect to use. See 25.3절. “Dialect resolution” for more information.

Hibernate's automatic session management for persistence contexts is particularly useful in this context. The hbm2ddl.auto option turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of the SchemaExport Ant task. Finally, add the mapping file(s) for persistent classes to the configuration.

Save this file as hibernate.cfg.xml into the src/main/resources directory.

We will now build the tutorial with Maven. You will need to have Maven installed; it is available from theMaven download page. Maven will read the /pom.xml file we created earlier and know how to perform some basic project tasks. First, lets run the compile goal to make sure we can compile everything so far:

[hibernateTutorial]$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building First Hibernate Tutorial
[INFO]    task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to /home/steve/projects/sandbox/hibernateTutorial/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009
[INFO] Final Memory: 5M/547M
[INFO] ------------------------------------------------------------------------

It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

We will create a HibernateUtil helper class that takes care of startup and makes accessing theorg.hibernate.SessionFactory more convenient.

package org.hibernate.tutorial.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Save this code as src/main/java/org/hibernate/tutorial/util/HibernateUtil.java

This class not only produces the global org.hibernate.SessionFactory reference in its static initializer; it also hides the fact that it uses a static singleton. We might just as well have looked up theorg.hibernate.SessionFactory reference from JNDI in an application server or any other location for that matter.

If you give the org.hibernate.SessionFactory a name in your configuration, Hibernate will try to bind it to JNDI under that name after it has been built. Another, better option is to use a JMX deployment and let the JMX-capable container instantiate and bind a HibernateService to JNDI. Such advanced options are discussed later.

You now need to configure a logging system. Hibernate uses commons logging and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copy log4j.properties from the Hibernate distribution in the etc/ directory to your src directory, next to hibernate.cfg.xml. If you prefer to have more verbose output than that provided in the example configuration, you can change the settings. By default, only the Hibernate startup message is shown on stdout.

The tutorial infrastructure is complete and you are now ready to do some real work with Hibernate.

We are now ready to start doing some real worjk with Hibernate. Let's start by writing an EventManagerclass with a main() method:

package org.hibernate.tutorial;

import org.hibernate.Session;

import java.util.*;

import org.hibernate.tutorial.domain.Event;
import org.hibernate.tutorial.util.HibernateUtil;

public class EventManager {

    public static void main(String[] args) {
        EventManager mgr = new EventManager();

        if (args[0].equals("store")) {
            mgr.createAndStoreEvent("My Event", new Date());
        }

        HibernateUtil.getSessionFactory().close();
    }

    private void createAndStoreEvent(String title, Date theDate) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);
        session.save(theEvent);

        session.getTransaction().commit();
    }

}

In createAndStoreEvent() we created a new Event object and handed it over to Hibernate. At that point, Hibernate takes care of the SQL and executes an INSERT on the database.

org.hibernate.Session is designed to represent a single unit of work (a single atmoic piece of work to be performed). For now we will keep things simple and assume a one-to-one granularity between a Hibernate org.hibernate.Session and a database transaction. To shield our code from the actual underlying transaction system we use the Hibernate org.hibernate.Transaction API. In this particular case we are using JDBC-based transactional semantics, but it could also run with JTA.

What does sessionFactory.getCurrentSession() do? First, you can call it as many times and anywhere you like once you get hold of your org.hibernate.SessionFactory. The getCurrentSession() method always returns the "current" unit of work. Remember that we switched the configuration option for this mechanism to "thread" in our src/main/resources/hibernate.cfg.xml? Due to that setting, the context of a current unit of work is bound to the current Java thread that executes the application.

org.hibernate.Session begins when the first call to getCurrentSession() is made for the current thread. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the org.hibernate.Session from the thread and closes it for you. If you call getCurrentSession() again, you get a new org.hibernate.Session and can start a new unit of work.

Related to the unit of work scope, should the Hibernate org.hibernate.Session be used to execute one or several database operations? The above example uses one org.hibernate.Session for one operation. However this is pure coincidence; the example is just not complex enough to show any other approach. The scope of a Hibernate org.hibernate.Session is flexible but you should never design your application to use a new Hibernate org.hibernate.Session for every database operation. Even though it is used in the following examples, consider session-per-operation an anti-pattern. A real web application is shown later in the tutorial which will help illustrate this.

See 11장. Transactions and Concurrency for more information about transaction handling and demarcation. The previous example also skipped any error handling and rollback.

To run this, we will make use of the Maven exec plugin to call our class with the necessary classpath setup:mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"

참고

You may need to perform mvn compile first.

You should see Hibernate starting up and, depending on your configuration, lots of log output. Towards the end, the following line will be displayed:

[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)

This is the INSERT executed by Hibernate.

To list stored events an option is added to the main method:

        if (args[0].equals("store")) {
            mgr.createAndStoreEvent("My Event", new Date());
        }
        else if (args[0].equals("list")) {
            List events = mgr.listEvents();
            for (int i = 0; i < events.size(); i++) {
                Event theEvent = (Event) events.get(i);
                System.out.println(
                        "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
                );
            }
        }

A new listEvents() method is also added:

    private List listEvents() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List result = session.createQuery("from Event").list();
        session.getTransaction().commit();
        return result;
    }

Here, we are using a Hibernate Query Language (HQL) query to load all existing Event objects from the database. Hibernate will generate the appropriate SQL, send it to the database and populate Eventobjects with the data. You can create more complex queries with HQL. See 14장. HQL: 하이버네이트 질의 언어(Hibernate Query Language) for more information.

Now we can call our new functionality, again using the Maven exec plugin:mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list"

So far we have mapped a single persistent entity class to a table in isolation. Let's expand on that a bit and add some class associations. We will add people to the application and store a list of events in which they participate.

By adding a collection of events to the Person class, you can easily navigate to the events for a particular person, without executing an explicit query - by calling Person#getEvents. Multi-valued associations are represented in Hibernate by one of the Java Collection Framework contracts; here we choose ajava.util.Set because the collection will not contain duplicate elements and the ordering is not relevant to our examples:

public class Person {

    private Set events = new HashSet();

    public Set getEvents() {
        return events;
    }

    public void setEvents(Set events) {
        this.events = events;
    }
}

Before mapping this association, let's consider the other side. We could just keep this unidirectional or create another collection on the Event, if we wanted to be able to navigate it from both directions. This is not necessary, from a functional perspective. You can always execute an explicit query to retrieve the participants for a particular event. This is a design choice left to you, but what is clear from this discussion is the multiplicity of the association: "many" valued on both sides is called a many-to-manyassociation. Hence, we use Hibernate's many-to-many mapping:

<class name="Person" table="PERSON">
    <id name="id" column="PERSON_ID">
        <generator class="native"/>
    </id>
    <property name="age"/>
    <property name="firstname"/>
    <property name="lastname"/>

    <set name="events" table="PERSON_EVENT">
        <key column="PERSON_ID"/>
        <many-to-many column="EVENT_ID" class="Event"/>
    </set>

</class>

Hibernate supports a broad range of collection mappings, a set being most common. For a many-to-many association, or n:m entity relationship, an association table is required. Each row in this table represents a link between a person and an event. The table name is decalred using the table attribute of the set element. The identifier column name in the association, for the person side, is defined with thekey element, the column name for the event's side with the column attribute of the many-to-many. You also have to tell Hibernate the class of the objects in your collection (the class on the other side of the collection of references).

따라서 이 매핑을 위한 데이터베이스 스키마는 다음과 같다:

    _____________        __________________
   |             |      |                  |       _____________
   |   EVENTS    |      |   PERSON_EVENT   |      |             |
   |_____________|      |__________________|      |    PERSON   |
   |             |      |                  |      |_____________|
   | *EVENT_ID   | <--> | *EVENT_ID        |      |             |
   |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  |
   |  TITLE      |      |__________________|      |  AGE        |
   |_____________|                                |  FIRSTNAME  |
                                                  |  LASTNAME   |
                                                  |_____________|
 

Now we will bring some people and events together in a new method in EventManager:

    private void addPersonToEvent(Long personId, Long eventId) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session.load(Person.class, personId);
        Event anEvent = (Event) session.load(Event.class, eventId);
        aPerson.getEvents().add(anEvent);

        session.getTransaction().commit();
    }

After loading a Person and an Event, simply modify the collection using the normal collection methods. There is no explicit call to update() or save(); Hibernate automatically detects that the collection has been modified and needs to be updated. This is called automatic dirty checking. You can also try it by modifying the name or the date property of any of your objects. As long as they are in persistent state, that is, bound to a particular Hibernate org.hibernate.Session, Hibernate monitors any changes and executes SQL in a write-behind fashion. The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is called flushing. In our code, the unit of work ends with a commit, or rollback, of the database transaction.

You can load person and event in different units of work. Or you can modify an object outside of aorg.hibernate.Session, when it is not in persistent state (if it was persistent before, this state is calleddetached). You can even modify a collection when it is detached:

    private void addPersonToEvent(Long personId, Long eventId) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session
                .createQuery("select p from Person p left join fetch p.events where p.id = :pid")
                .setParameter("pid", personId)
                .uniqueResult(); // Eager fetch the collection so we can use it detached
        Event anEvent = (Event) session.load(Event.class, eventId);

        session.getTransaction().commit();

        // End of first unit of work

        aPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached

        // Begin second unit of work

        Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
        session2.beginTransaction();
        session2.update(aPerson); // Reattachment of aPerson

        session2.getTransaction().commit();
    }

The call to update makes a detached object persistent again by binding it to a new unit of work, so any modifications you made to it while detached can be saved to the database. This includes any modifications (additions/deletions) you made to a collection of that entity object.

This is not much use in our example, but it is an important concept you can incorporate into your own application. Complete this exercise by adding a new action to the main method of the EventManager and call it from the command line. If you need the identifiers of a person and an event - the save() method returns it (you might have to modify some of the previous methods to return that identifier):

        else if (args[0].equals("addpersontoevent")) {
            Long eventId = mgr.createAndStoreEvent("My Event", new Date());
            Long personId = mgr.createAndStorePerson("Foo", "Bar");
            mgr.addPersonToEvent(personId, eventId);
            System.out.println("Added person " + personId + " to event " + eventId);
        }

This is an example of an association between two equally important classes : two entities. As mentioned earlier, there are other classes and types in a typical model, usually "less important". Some you have already seen, like an int or a java.lang.String. We call these classes value types, and their instances depend on a particular entity. Instances of these types do not have their own identity, nor are they shared between entities. Two persons do not reference the same firstname object, even if they have the same first name. Value types cannot only be found in the JDK , but you can also write dependent classes yourself such as an Address or MonetaryAmount class. In fact, in a Hibernate application all JDK classes are considered value types.

You can also design a collection of value types. This is conceptually different from a collection of references to other entities, but looks almost the same in Java.

Let's add a collection of email addresses to the Person entity. This will be represented as a java.util.Set ofjava.lang.String instances:

    private Set emailAddresses = new HashSet();

    public Set getEmailAddresses() {
        return emailAddresses;
    }

    public void setEmailAddresses(Set emailAddresses) {
        this.emailAddresses = emailAddresses;
    }

The mapping of this Set is as follows:

        <set name="emailAddresses" table="PERSON_EMAIL_ADDR">
            <key column="PERSON_ID"/>
            <element type="string" column="EMAIL_ADDR"/>
        </set>

The difference compared with the earlier mapping is the use of the element part which tells Hibernate that the collection does not contain references to another entity, but is rather a collection whose elements are values types, here specifically of type string. The lowercase name tells you it is a Hibernate mapping type/converter. Again the table attribute of the set element determines the table name for the collection. The key element defines the foreign-key column name in the collection table. The columnattribute in the element element defines the column name where the email address values will actually be stored.

Here is the updated schema:

  _____________        __________________
 |             |      |                  |       _____________
 |   EVENTS    |      |   PERSON_EVENT   |      |             |       ___________________
 |_____________|      |__________________|      |    PERSON   |      |                   |
 |             |      |                  |      |_____________|      | PERSON_EMAIL_ADDR |
 | *EVENT_ID   | <--> | *EVENT_ID        |      |             |      |___________________|
 |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  | <--> |  *PERSON_ID       |
 |  TITLE      |      |__________________|      |  AGE        |      |  *EMAIL_ADDR      |
 |_____________|                                |  FIRSTNAME  |      |___________________|
                                                |  LASTNAME   |
                                                |_____________|
 

You can see that the primary key of the collection table is in fact a composite key that uses both columns. This also implies that there cannot be duplicate email addresses per person, which is exactly the semantics we need for a set in Java.

You can now try to add elements to this collection, just like we did before by linking persons and events. It is the same code in Java:

    private void addEmailToPerson(Long personId, String emailAddress) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session.load(Person.class, personId);
        // adding to the emailAddress collection might trigger a lazy load of the collection
        aPerson.getEmailAddresses().add(emailAddress);

        session.getTransaction().commit();
    }

This time we did not use a fetch query to initialize the collection. Monitor the SQL log and try to optimize this with an eager fetch.

First, keep in mind that Hibernate does not affect normal Java semantics. How did we create a link between a Person and an Event in the unidirectional example? You add an instance of Event to the collection of event references, of an instance of Person. If you want to make this link bi-directional, you have to do the same on the other side by adding a Person reference to the collection in an Event. This process of "setting the link on both sides" is absolutely necessary with bi-directional links.

Many developers program defensively and create link management methods to correctly set both sides (for example, in Person):

    protected Set getEvents() {
        return events;
    }

    protected void setEvents(Set events) {
        this.events = events;
    }

    public void addToEvent(Event event) {
        this.getEvents().add(event);
        event.getParticipants().add(this);
    }

    public void removeFromEvent(Event event) {
        this.getEvents().remove(event);
        event.getParticipants().remove(this);
    }

The get and set methods for the collection are now protected. This allows classes in the same package and subclasses to still access the methods, but prevents everybody else from altering the collections directly. Repeat the steps for the collection on the other side.

What about the inverse mapping attribute? For you, and for Java, a bi-directional link is simply a matter of setting the references on both sides correctly. Hibernate, however, does not have enough information to correctly arrange SQL INSERT and UPDATE statements (to avoid constraint violations). Making one side of the association inverse tells Hibernate to consider it a mirror of the other side. That is all that is necessary for Hibernate to resolve any issues that arise when transforming a directional navigation model to a SQL database schema. The rules are straightforward: all bi-directional associations need one side as inverse. In a one-to-many association it has to be the many-side, and in many-to-many association you can select either side.

A Hibernate web application uses Session and Transaction almost like a standalone application. However, some common patterns are useful. You can now write an EventManagerServlet. This servlet can list all events stored in the database, and it provides an HTML form to enter new events.

First we need create our basic processing servlet. Since our servlet only handles HTTP GET requests, we will only implement the doGet() method:

package org.hibernate.tutorial.web;

// Imports

public class EventManagerServlet extends HttpServlet {

    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );

        try {
            // Begin unit of work
            HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

            // Process request and render page...

            // End unit of work
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
        }
        catch (Exception ex) {
            HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
            if ( ServletException.class.isInstance( ex ) ) {
                throw ( ServletException ) ex;
            }
            else {
                throw new ServletException( ex );
            }
        }
    }

}

Save this servlet as src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java

The pattern applied here is called session-per-request. When a request hits the servlet, a new HibernateSession is opened through the first call to getCurrentSession() on the SessionFactory. A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications.

모든 데이터베이스 오퍼레이션 각각에 대해 새로운 Hibernate Session을 사용하지 말라. 전체 요청에 대해 영역지워진 한 개의 Hibernate Session을 사용하라. 그것이 자동적으로 현재의 자바 쓰레드에 바인드되도록 getCurrentSession()을 사용하라.

Next, the possible actions of the request are processed and the response HTML is rendered. We will get to that part soon.

Finally, the unit of work ends when processing and rendering are complete. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back. This completes the session-per-request pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern called Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.

Now you can implement the processing of the request and the rendering of the page.

        // Write HTML header
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>Event Manager</title></head><body>");

        // Handle actions
        if ( "store".equals(request.getParameter("action")) ) {

            String eventTitle = request.getParameter("eventTitle");
            String eventDate = request.getParameter("eventDate");

            if ( "".equals(eventTitle) || "".equals(eventDate) ) {
                out.println("<b><i>Please enter event title and date.</i></b>");
            }
            else {
                createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
                out.println("<b><i>Added event.</i></b>");
            }
        }

        // Print page
       printEventForm(out);
       listEvents(out, dateFormatter);

       // Write HTML footer
       out.println("</body></html>");
       out.flush();
       out.close();

This coding style, with a mix of Java and HTML, would not scale in a more complex application-keep in mind that we are only illustrating basic Hibernate concepts in this tutorial. The code prints an HTML header and a footer. Inside this page, an HTML form for event entry and a list of all events in the database are printed. The first method is trivial and only outputs HTML:

    private void printEventForm(PrintWriter out) {
        out.println("<h2>Add new event:</h2>");
        out.println("<form>");
        out.println("Title: <input name='eventTitle' length='50'/><br/>");
        out.println("Date (e.g. 24.12.2009): <input name='eventDate' length='10'/><br/>");
        out.println("<input type='submit' name='action' value='store'/>");
        out.println("</form>");
    }

listEvents() 메소드는 하나의 질의를 실행하기 위해서 현재의 쓰레드에 결합된 Hibernate Session을 사용한다:

    private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {

        List result = HibernateUtil.getSessionFactory()
                .getCurrentSession().createCriteria(Event.class).list();
        if (result.size() > 0) {
            out.println("<h2>Events in database:</h2>");
            out.println("<table border='1'>");
            out.println("<tr>");
            out.println("<th>Event title</th>");
            out.println("<th>Event date</th>");
            out.println("</tr>");
            Iterator it = result.iterator();
            while (it.hasNext()) {
                Event event = (Event) it.next();
                out.println("<tr>");
                out.println("<td>" + event.getTitle() + "</td>");
                out.println("<td>" + dateFormatter.format(event.getDate()) + "</td>");
                out.println("</tr>");
            }
            out.println("</table>");
        }
    }

마지막으로, store 액션은 createAndStoreEvent() 메소드로 디스패치된다. 그것은 현재 쓰레드의 Session을 사용한다:

    protected void createAndStoreEvent(String title, Date theDate) {
        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);

        HibernateUtil.getSessionFactory()
                .getCurrentSession().save(theEvent);
    }

The servlet is now complete. A request to the servlet will be processed in a single Session andTransaction. As earlier in the standalone application, Hibernate can automatically bind these objects to the current thread of execution. This gives you the freedom to layer your code and access theSessionFactory in any way you like. Usually you would use a more sophisticated design and move the data access code into data access objects (the DAO pattern). See the Hibernate Wiki for more examples.

To deploy this application for testing we must create a Web ARchive (WAR). First we must define the WAR descriptor as src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>Event Manager</servlet-name>
        <servlet-class>org.hibernate.tutorial.web.EventManagerServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Event Manager</servlet-name>
        <url-pattern>/eventmanager</url-pattern>
    </servlet-mapping>
</web-app>

To build and deploy call mvn package in your project directory and copy the hibernate-tutorial.war file into your Tomcat webapps directory.

참고

If you do not have Tomcat installed, download it from http://tomcat.apache.org/ and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration.

일단 배치했고 Tomcat이 실행중이면, http://localhost:8080/hibernate-tutorial/eventmanager로 어플리케이션에 접근하라. 첫 번째 요청이 당신의 서블릿에 도달할 때 Hibernate가 초기화(HibernateUtil 내에 있는 static initializer가 호출된다) 되는 것을 보기 위해 그리고 만일 어떤 예외상황들이 발생할 경우 상세한 출력을 얻기 위해서 Tomcat 로그를 지켜보도록 하라.

The diagram below provides a high-level view of the Hibernate architecture:

We do not have the scope in this document to provide a more detailed view of all the runtime architectures available; Hibernate is flexible and supports several different approaches. We will, however, show the two extremes: "minimal" architecture and "comprehensive" architecture.

This next diagram illustrates how Hibernate utilizes database and configuration data to provide persistence services, and persistent objects, to the application.

The "minimal" architecture has the application provide its own JDBC connections and manage its own transactions. This approach uses a minimal subset of Hibernate's APIs:

The "comprehensive" architecture abstracts the application away from the underlying JDBC/JTA APIs and allows Hibernate to manage the details.

Here are some definitions of the objects depicted in the diagrams:

SessionFactory (org.hibernate.SessionFactory)

A threadsafe, immutable cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProviderSessionFactory can hold an optional (second-level) cache of data that is reusable between transactions at a process, or cluster, level.

Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps a JDBC connection and is a factory for TransactionSession holds a mandatory first-level cache of persistent objects that are used when navigating the object graph or looking up objects by identifier.

영속 객체들과 콜렉션들

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one Session. Once the Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

전이(Transient, 필자 주-과도) 객체들과 콜렉션들

Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed Session.

Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A Sessionmight span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional.

ConnectionProvider (org.hibernate.connection.ConnectionProvider)

(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlyingDatasource or DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

TransactionFactory (org.hibernate.TransactionFactory)

(Optional) A factory for Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

Extension Interfaces

Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.

Given a "minimal" architecture, the application bypasses the Transaction/TransactionFactory and/orConnectionProvider APIs to communicate with JTA or JDBC directly.

JMX is the J2EE standard for the management of Java components. Hibernate can be managed via a JMX standard service. AN MBean implementation is provided in the distribution:org.hibernate.jmx.HibernateService.

For an example of how to deploy Hibernate as a JMX service on the JBoss Application Server, please see the JBoss User Guide. JBoss AS also provides these benefits if you deploy using JMX:

이들 옵션들에 대한 추가 정보는 JBoss 어플리케이션 서버 사용자 가이드를 참조하라.

Another feature available as a JMX service is runtime Hibernate statistics. See 3.4.6절. “Hibernate 통계”for more information.

Most applications using Hibernate need some form of "contextual" session, where a given session is in effect throughout the scope of a given context. However, across applications the definition of what constitutes a context is typically different; different contexts define different scopes to the notion of current. Applications using Hibernate prior to version 3.0 tended to utilize either home-grownThreadLocal-based contextual sessions, helper classes such as HibernateUtil, or utilized third-party frameworks, such as Spring or Pico, which provided proxy/interception-based contextual sessions.

Starting with version 3.0.1, Hibernate added the SessionFactory.getCurrentSession() method. Initially, this assumed usage of JTA transactions, where the JTA transaction defined both the scope and context of a current session. Given the maturity of the numerous stand-alone JTA TransactionManagerimplementations, most, if not all, applications should be using JTA transaction management, whether or not they are deployed into a J2EE container. Based on that, the JTA-based contextual sessions are all you need to use.

However, as of version 3.1, the processing behind SessionFactory.getCurrentSession() is now pluggable. To that end, a new extension interface, org.hibernate.context.CurrentSessionContext, and a new configuration parameter, hibernate.current_session_context_class, have been added to allow pluggability of the scope and context of defining current sessions.

See the Javadocs for the org.hibernate.context.CurrentSessionContext interface for a detailed discussion of its contract. It defines a single method, currentSession(), by which the implementation is responsible for tracking the current contextual session. Out-of-the-box, Hibernate comes with three implementations of this interface:

The first two implementations provide a "one session - one database transaction" programming model. This is also also known and used as session-per-request. The beginning and end of a Hibernate session is defined by the duration of a database transaction. If you use programmatic transaction demarcation in plain JSE without JTA, you are advised to use the Hibernate Transaction API to hide the underlying transaction system from your code. If you use JTA, you can utilize the JTA interfaces to demarcate transactions. If you execute in an EJB container that supports CMT, transaction boundaries are defined declaratively and you do not need any transaction or session demarcation operations in your code. Refer to 11장. Transactions and Concurrency for more information and code examples.

The hibernate.current_session_context_class configuration parameter defines whichorg.hibernate.context.CurrentSessionContext implementation should be used. For backwards compatibility, if this configuration parameter is not set but a org.hibernate.transaction.TransactionManagerLookup is configured, Hibernate will use the org.hibernate.context.JTASessionContext. Typically, the value of this parameter would just name the implementation class to use. For the three out-of-the-box implementations, however, there are three corresponding short names: "jta", "thread", and "managed".

Hibernate is designed to operate in many different environments and, as such, there is a broad range of configuration parameters. Fortunately, most have sensible default values and Hibernate is distributed with an example hibernate.properties file in etc/ that displays the various options. Simply put the example file in your classpath and customize it to suit your needs.

An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutableorg.hibernate.SessionFactory. The mappings are compiled from various XML mapping files.

You can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:

Configuration cfg = new Configuration()
    .addResource("Item.hbm.xml")
    .addResource("Bid.hbm.xml");

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);

Hibernate will then search for mapping files named /org/hibernate/auction/Item.hbm.xml and/org/hibernate/auction/Bid.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.

org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

This is not the only way to pass configuration properties to Hibernate. Some alternative options include:

If you want to get started quicklyhibernate.properties is the easiest approach.

The org.hibernate.cfg.Configuration is intended as a startup-time object that will be discarded once aSessionFactory is created.

It is advisable to have the org.hibernate.SessionFactory create and pool JDBC connections for you. If you take this approach, opening a org.hibernate.Session is as simple as:

Session session = sessions.openSession(); // open a new Session

Once you start a task that requires access to the database, a JDBC connection will be obtained from the pool.

Before you can do this, you first need to pass some JDBC connection properties to Hibernate. All Hibernate property names and semantics are defined on the class org.hibernate.cfg.Environment. The most important settings for JDBC connection configuration are outlined below.

Hibernate will obtain and pool connections using java.sql.DriverManager if you set the following properties:


Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace thehibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate will use its org.hibernate.connection.C3P0ConnectionProvider for connection pooling if you sethibernate.c3p0.* properties. If you would like to use Proxool, refer to the packagedhibernate.properties and the Hibernate web site for more information.

The following is an example hibernate.properties file for c3p0:

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server javax.sql.Datasource registered in JNDI. You will need to set at least one of the following properties:


Here is an example hibernate.properties file for an application server provided JNDI datasource:

hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

JNDI datasource로부터 얻어진 JDBC 커넥션들은 어플리케이션 서버의 컨테이너에 의해 관리되는 트랜잭션들에 자동적으로 참여할 것이다.

Arbitrary connection properties can be given by prepending "hibernate.connection" to the connection property name. For example, you can specify a charSet connection property usinghibernate.connection.charSet.

You can define your own plugin strategy for obtaining JDBC connections by implementing the interfaceorg.hibernate.connection.ConnectionProvider, and specifying your custom implementation via thehibernate.connection.provider_class property.

There are a number of other properties that control the behavior of Hibernate at runtime. All are optional and have reasonable default values.

표 3.3. Hibernate 구성 프로퍼티들

프로퍼티 이름용도
hibernate.dialectThe classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.

e.g. full.classname.of.Dialect

In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect implementation based on theJDBC metadata returned by the JDBC driver.

hibernate.show_sqlWrite all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

e.g. true | false

hibernate.format_sqlPretty print the SQL in the log and console. 

e.g. true | false

hibernate.default_schemaQualify unqualified table names with the given schema/tablespace in generated SQL. 

e.g. SCHEMA_NAME

hibernate.default_catalogQualifies unqualified table names with the given catalog in generated SQL. 

e.g. CATALOG_NAME

hibernate.session_factory_nameThe org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created.

e.g. jndi/composite/name

hibernate.max_fetch_depthSets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.

e.g. recommended values between 0 and 3

hibernate.default_batch_fetch_sizeSets a default size for Hibernate batch fetching of associations.

e.g. recommended values 4816

hibernate.default_entity_modeSets a default mode for entity representation for all sessions opened from this SessionFactory

dynamic-mapdom4jpojo

hibernate.order_updatesForces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems. 

e.g. true | false

hibernate.generate_statisticsIf enabled, Hibernate will collect statistics useful for performance tuning. 

e.g. true | false

hibernate.use_identifer_rollbackIf enabled, generated identifier properties will be reset to default values when objects are deleted. 

e.g. true | false

hibernate.use_sql_commentsIf turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false.

e.g. true | false


표 3.4. Hibernate JDBC 및 커넥션 프로퍼티들

프로퍼티 이름용도
hibernate.jdbc.fetch_sizeA non-zero value determines the JDBC fetch size (callsStatement.setFetchSize()).
hibernate.jdbc.batch_sizeA non-zero value enables use of JDBC2 batch updates by Hibernate. 

e.g. recommended values between 5 and 30

hibernate.jdbc.batch_versioned_dataSet this property to true if your JDBC driver returns correct row counts from executeBatch(). Iit is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false.

e.g. true | false

hibernate.jdbc.factory_classSelect a custom org.hibernate.jdbc.Batcher. Most applications will not need this configuration property.

e.g. classname.of.BatcherFactory

hibernate.jdbc.use_scrollable_resultsetEnables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise. 

e.g. true | false

hibernate.jdbc.use_streams_for_binaryUse streams when writing/reading binary or serializabletypes to/from JDBC. *system-level property*

e.g. true | false

hibernate.jdbc.use_get_generated_keysEnables use of JDBC3 PreparedStatement.getGeneratedKeys()to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, it tries to determine the driver capabilities using connection metadata.

e.g. true|false

hibernate.connection.provider_classThe classname of a customorg.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.

e.g. classname.of.ConnectionProvider

hibernate.connection.isolationSets the JDBC transaction isolation level. Checkjava.sql.Connection for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations.

e.g. 1, 2, 4, 8

hibernate.connection.autocommitEnables autocommit for JDBC pooled connections (it is not recommended). 

e.g. true | false

hibernate.connection.release_modeSpecifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transactionauto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy.

e.g. auto (default) | on_close | after_transaction |after_statement

This setting only affects Sessions returned fromSessionFactory.openSession. For Sessions obtained throughSessionFactory.getCurrentSession, the CurrentSessionContextimplementation configured for use controls the connection release mode for those Sessions. See 2.5절. “Contextual sessions”

hibernate.connection.<propertyName>Pass the JDBC property <propertyName> toDriverManager.getConnection().
hibernate.jndi.<propertyName>Pass the property <propertyName> to the JNDIInitialContextFactory.




Hibernate utilizes Simple Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direct your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on your chosen binding. In order to setup logging you will needslf4j-api.jar in your classpath together with the jar file for your preferred binding - slf4j-log4j12.jar in the case of Log4J. See the SLF4J documentation for more detail. To use Log4j you will also need to place a log4j.properties file in your classpath. An example properties file is distributed with Hibernate in thesrc/ directory.

It is recommended that you familiarize yourself with Hibernate's log messages. A lot of work has been put into making the Hibernate log as detailed as possible, without making it unreadable. It is an essential troubleshooting device. The most interesting log categories are the following:


Hibernate로 어플리케이션들을 개발할 때, 당신은 거의 항상 org.hibernate.SQL 카테고리에 대해 이용 가능한 debug 모드로 작업하거나, 다른 방법으로 hibernate.show_sql 프로퍼티를 이용가능하게 하여 작업해야 할 것이다.

구성에 대한 다른 접근법은 hibernate.cfg.xml로 명명된 파일 속에 전체 구성을 지정하는 것이다. 이 파일은hibernate.properties 파일에 대한 대용물로서 사용될 수 있거나, 만일 둘 다 존재할 경우에 프로퍼티들을 중복정의하는데 사용될 수 있다.

The XML configuration file is by default expected to be in the root of your CLASSPATH. Here is an example:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory
        name="java:hibernate/SessionFactory">

        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="org/hibernate/auction/Item.hbm.xml"/>
        <mapping resource="org/hibernate/auction/Bid.hbm.xml"/>

        <!-- cache settings -->
        <class-cache class="org.hibernate.auction.Item" usage="read-write"/>
        <class-cache class="org.hibernate.auction.Bid" usage="read-only"/>
        <collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>

    </session-factory>

</hibernate-configuration>

The advantage of this approach is the externalization of the mapping file names to configuration. Thehibernate.cfg.xml is also more convenient once you have to tune the Hibernate cache. It is your choice to use either hibernate.properties or hibernate.cfg.xml. Both are equivalent, except for the above mentioned benefits of using the XML syntax.

With the XML configuration, starting Hibernate is then as simple as:

SessionFactory sf = new Configuration().configure().buildSessionFactory();

You can select a different XML configuration file using:

SessionFactory sf = new Configuration()
    .configure("catdb.cfg.xml")
    .buildSessionFactory();

Hibernate는 J2EE 인프라스트럭처에 대한 다음 통합 점들을 갖고 있다:

당신의 환경에 따라, 당신은 당신의 어플리케이션 서버가 "connection containment(연결 봉쇄)" 예외상황들을 보일 경우에 구성 옵션 hibernate.connection.aggressive_release를 true로 설정해야 될 수도 있다.

The Hibernate Session API is independent of any transaction demarcation system in your architecture. If you let Hibernate use JDBC directly through a connection pool, you can begin and end your transactions by calling the JDBC API. If you run in a J2EE application server, you might want to use bean-managed transactions and call the JTA API and UserTransaction when needed.

이들 두 개의 (그리고 다른) 환경들에서 당신의 코드에 이식성을 유지하기 위해 우리는 기본 시스템을 포장하고 은폐시키는 선택적인 Hibernate Transaction API를 권장한다. 당신은 Hibernate 구성 프로퍼티hibernate.transaction.factory_class를 사용하여 Transaction 인스턴스들에 대한 팩토리 클래스를 지정해야 한다.

There are three standard, or built-in, choices:

You can also define your own transaction strategies (for a CORBA transaction service, for example).

Some features in Hibernate (i.e., the second level cache, Contextual Sessions with JTA, etc.) require access to the JTA TransactionManager in a managed environment. In an application server, since J2EE does not standardize a single mechanism, you have to specify how Hibernate should obtain a reference to the TransactionManager:


A JNDI-bound Hibernate SessionFactory can simplify the lookup function of the factory and create newSessions. This is not, however, related to a JNDI bound Datasource; both simply use the same registry.

If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (e.g.java:hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. This is especially useful in environments with a read-only JNDI default implementation (in Tomcat, for example).

SessionFactory를 JNDI에 바인드 시킬 때, Hibernate는 초기 컨텍스트를 초기화 시키기 위해 hibernate.jndi.url,hibernate.jndi.class의 값들을 사용할 것이다. 만일 그것들이 지정되어 있지 않을 경우, 디폴트 InitialContext가 사용될 것이다.

Hibernate will automatically place the SessionFactory in JNDI after you call cfg.buildSessionFactory(). This means you will have this call in some startup code, or utility class in your application, unless you use JMX deployment with the HibernateService (this is discussed later in greater detail).

If you use a JNDI SessionFactory, an EJB or any other class, you can obtain the SessionFactory using a JNDI lookup.

It is recommended that you bind the SessionFactory to JNDI in a managed environment and use a staticsingleton otherwise. To shield your application code from these details, we also recommend to hide the actual lookup code for a SessionFactory in a helper class, such as HibernateUtil.getSessionFactory(). Note that such a class is also a convenient way to startup Hibernatesee chapter 1.

The easiest way to handle Sessions and transactions is Hibernate's automatic "current" Sessionmanagement. For a discussion of contextual sessions see 2.5절. “Contextual sessions”. Using the "jta"session context, if there is no Hibernate Session associated with the current JTA transaction, one will be started and associated with that JTA transaction the first time you call sessionFactory.getCurrentSession(). The Sessions retrieved via getCurrentSession() in the"jta" context are set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement. This allows the Sessions to be managed by the life cycle of the JTA transaction to which it is associated, keeping user code clean of such management concerns. Your code can either use JTA programmatically through UserTransaction, or (recommended for portable code) use the Hibernate Transaction API to set transaction boundaries. If you run in an EJB container, declarative transaction demarcation with CMT is preferred.

The line cfg.buildSessionFactory() still has to be executed somewhere to get a SessionFactory into JNDI. You can do this either in a static initializer block, like the one in HibernateUtil, or you can deploy Hibernate as a managed service.

Hibernate is distributed with org.hibernate.jmx.HibernateService for deployment on an application server with JMX capabilities, such as JBoss AS. The actual deployment and configuration is vendor-specific. Here is an example jboss-service.xml for JBoss 4.0.x:

<?xml version="1.0"?>
<server>

<mbean code="org.hibernate.jmx.HibernateService"
    name="jboss.jca:service=HibernateFactory,name=HibernateFactory">

    <!-- Required services -->
    <depends>jboss.jca:service=RARDeployer</depends>
    <depends>jboss.jca:service=LocalTxCM,name=HsqlDS</depends>

    <!-- Bind the Hibernate service to JNDI -->
    <attribute name="JndiName">java:/hibernate/SessionFactory</attribute>

    <!-- Datasource settings -->
    <attribute name="Datasource">java:HsqlDS</attribute>
    <attribute name="Dialect">org.hibernate.dialect.HSQLDialect</attribute>

    <!-- Transaction integration -->
    <attribute name="TransactionStrategy">
        org.hibernate.transaction.JTATransactionFactory</attribute>
    <attribute name="TransactionManagerLookupStrategy">
        org.hibernate.transaction.JBossTransactionManagerLookup</attribute>
    <attribute name="FlushBeforeCompletionEnabled">true</attribute>
    <attribute name="AutoCloseSessionEnabled">true</attribute>

    <!-- Fetching options -->
    <attribute name="MaximumFetchDepth">5</attribute>

    <!-- Second-level caching -->
    <attribute name="SecondLevelCacheEnabled">true</attribute>
    <attribute name="CacheProviderClass">org.hibernate.cache.EhCacheProvider</attribute>
    <attribute name="QueryCacheEnabled">true</attribute>

    <!-- Logging -->
    <attribute name="ShowSqlEnabled">true</attribute>

    <!-- Mapping files -->
    <attribute name="MapResources">auction/Item.hbm.xml,auction/Category.hbm.xml</attribute>

</mbean>

</server>

This file is deployed in a directory called META-INF and packaged in a JAR file with the extension .sar(service archive). You also need to package Hibernate, its required third-party libraries, your compiled persistent classes, as well as your mapping files in the same archive. Your enterprise beans (usually session beans) can be kept in their own JAR file, but you can include this EJB JAR file in the main service archive to get a single (hot-)deployable unit. Consult the JBoss AS documentation for more information about JMX service and EJB deployment.

Persistent classes are classes in an application that implement the entities of the business problem (e.g. Customer and Order in an E-commerce application). Not all instances of a persistent class are considered to be in the persistent state. For example, an instance can instead be transient or detached.

Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. However, none of these rules are hard requirements. Indeed, Hibernate3 assumes very little about the nature of your persistent objects. You can express a domain model in other ways (using trees of Map instances, for example).

Most Java applications require a persistent class representing felines. For example:

package eg;
import java.util.Set;
import java.util.Date;

public class Cat {
    private Long id; // identifier

    private Date birthdate;
    private Color color;
    private char sex;
    private float weight;
    private int litterId;

    private Cat mother;
    private Set kittens = new HashSet();

    private void setId(Long id) {
        this.id=id;
    }
    public Long getId() {
        return id;
    }

    void setBirthdate(Date date) {
        birthdate = date;
    }
    public Date getBirthdate() {
        return birthdate;
    }

    void setWeight(float weight) {
        this.weight = weight;
    }
    public float getWeight() {
        return weight;
    }

    public Color getColor() {
        return color;
    }
    void setColor(Color color) {
        this.color = color;
    }

    void setSex(char sex) {
        this.sex=sex;
    }
    public char getSex() {
        return sex;
    }

    void setLitterId(int id) {
        this.litterId = id;
    }
    public int getLitterId() {
        return litterId;
    }

    void setMother(Cat mother) {
        this.mother = mother;
    }
    public Cat getMother() {
        return mother;
    }
    void setKittens(Set kittens) {
        this.kittens = kittens;
    }
    public Set getKittens() {
        return kittens;
    }
    
    // addKitten not needed by Hibernate
    public void addKitten(Cat kitten) {
            kitten.setMother(this);
        kitten.setLitterId( kittens.size() ); 
        kittens.add(kitten);
    }
}

The four main rules of persistent classes are explored in more detail in the following sections.

You have to override the equals() and hashCode() methods if you:

Hibernate guarantees equivalence of persistent identity (database row) and Java identity only inside a particular session scope. When you mix instances retrieved in different sessions, you must implementequals() and hashCode() if you wish to have meaningful semantics for Sets.

The most obvious way is to implement equals()/hashCode() by comparing the identifier value of both objects. If the value is the same, both must be the same database row, because they are equal. If both are added to a Set, you will only have one element in the Set). Unfortunately, you cannot use that approach with generated identifiers. Hibernate will only assign identifier values to objects that are persistent; a newly created instance will not have any identifier value. Furthermore, if an instance is unsaved and currently in a Set, saving it will assign an identifier value to the object. If equals() andhashCode() are based on the identifier value, the hash code would change, breaking the contract of theSet. See the Hibernate website for a full discussion of this problem. This is not a Hibernate issue, but normal Java semantics of object identity and equality.

It is recommended that you implement equals() and hashCode() using Business key equality. Business key equality means that the equals() method compares only the properties that form the business key. It is a key that would identify our instance in the real world (a natural candidate key):

public class Cat {

    ...
    public boolean equals(Object other) {
        if (this == other) return true;
        if ( !(other instanceof Cat) ) return false;

        final Cat cat = (Cat) other;

        if ( !cat.getLitterId().equals( getLitterId() ) ) return false;
        if ( !cat.getMother().equals( getMother() ) ) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = getMother().hashCode();
        result = 29 * result + getLitterId();
        return result;
    }

}

A business key does not have to be as solid as a database primary key candidate (see 11.1.3절. “객체 identity 고려하기”). Immutable or unique properties are usually good candidates for a business key.

Persistent entities do not necessarily have to be represented as POJO classes or as JavaBean objects at runtime. Hibernate also supports dynamic models (using Maps of Maps at runtime) and the representation of entities as DOM4J trees. With this approach, you do not write persistent classes, only mapping files.

By default, Hibernate works in normal POJO mode. You can set a default entity representation mode for a particular SessionFactory using the default_entity_mode configuration option (see 표 3.3. “Hibernate 구성 프로퍼티들”).

The following examples demonstrate the representation using Maps. First, in the mapping file anentity-name has to be declared instead of, or in addition to, a class name:

<hibernate-mapping>

    <class entity-name="Customer">

        <id name="id"
            type="long"
            column="ID">
            <generator class="sequence"/>
        </id>

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

        <property name="address"
            column="ADDRESS"
            type="string"/>

        <many-to-one name="organization"
            column="ORGANIZATION_ID"
            class="Organization"/>

        <bag name="orders"
            inverse="true"
            lazy="false"
            cascade="all">
            <key column="CUSTOMER_ID"/>
            <one-to-many class="Order"/>
        </bag>

    </class>
    
</hibernate-mapping>

Even though associations are declared using target class names, the target type of associations can also be a dynamic entity instead of a POJO.

After setting the default entity mode to dynamic-map for the SessionFactory, you can, at runtime, work with Maps of Maps:

Session s = openSession();
Transaction tx = s.beginTransaction();
Session s = openSession();

// Create a customer
Map david = new HashMap();
david.put("name", "David");

// Create an organization
Map foobar = new HashMap();
foobar.put("name", "Foobar Inc.");

// Link both
david.put("organization", foobar);

// Save both
s.save("Customer", david);
s.save("Organization", foobar);

tx.commit();
s.close();

One of the main advantages of dynamic mapping is quick turnaround time for prototyping, without the need for entity class implementation. However, you lose compile-time type checking and will likely deal with many exceptions at runtime. As a result of the Hibernate mapping, the database schema can easily be normalized and sound, allowing to add a proper domain model implementation on top later on.

엔티티 표현 모드들은 또한 하나의 단위 Session 기준에 대해 설정될 수 있다:

Session dynamicSession = pojoSession.getSession(EntityMode.MAP);

// Create a customer
Map david = new HashMap();
david.put("name", "David");
dynamicSession.save("Customer", david);
...
dynamicSession.flush();
dynamicSession.close()
...
// Continue on pojoSession

Please note that the call to getSession() using an EntityMode is on the Session API, not the SessionFactory. That way, the new Session shares the underlying JDBC connection, transaction, and other context information. This means you do not have to call flush() and close() on the secondary Session, and also leave the transaction and connection handling to the primary unit of work.

XML 표현 가용성들에 대한 추가 정보는 18장. XML 매핑에서 찾을 수 있다.

org.hibernate.tuple.Tuplizer, and its sub-interfaces, are responsible for managing a particular representation of a piece of data given that representation's org.hibernate.EntityMode. If a given piece of data is thought of as a data structure, then a tuplizer is the thing that knows how to create such a data structure and how to extract values from and inject values into such a data structure. For example, for the POJO entity mode, the corresponding tuplizer knows how create the POJO through its constructor. It also knows how to access the POJO properties using the defined property accessors.

There are two high-level types of Tuplizers, represented by the org.hibernate.tuple.entity.EntityTuplizer andorg.hibernate.tuple.component.ComponentTuplizer interfaces. EntityTuplizers are responsible for managing the above mentioned contracts in regards to entities, while ComponentTuplizers do the same for components.

Users can also plug in their own tuplizers. Perhaps you require that a java.util.Map implementation other than java.util.HashMap be used while in the dynamic-map entity-mode. Or perhaps you need to define a different proxy generation strategy than the one used by default. Both would be achieved by defining a custom tuplizer implementation. Tuplizer definitions are attached to the entity or component mapping they are meant to manage. Going back to the example of our customer entity:

<hibernate-mapping>
    <class entity-name="Customer">
        <!--
            Override the dynamic-map entity-mode
            tuplizer for the customer entity
        -->
        <tuplizer entity-mode="dynamic-map"
                class="CustomMapTuplizerImpl"/>

        <id name="id" type="long" column="ID">
            <generator class="sequence"/>
        </id>

        <!-- other properties -->
        ...
    </class>
</hibernate-mapping>


public class CustomMapTuplizerImpl
        extends org.hibernate.tuple.entity.DynamicMapEntityTuplizer {
    // override the buildInstantiator() method to plug in our custom map...
    protected final Instantiator buildInstantiator(
            org.hibernate.mapping.PersistentClass mappingInfo) {
        return new CustomMapInstantiator( mappingInfo );
    }

    private static final class CustomMapInstantiator
            extends org.hibernate.tuple.DynamicMapInstantitor {
        // override the generateMap() method to return our custom map...
            protected final Map generateMap() {
                    return new CustomMap();
            }
    }
}

The org.hibernate.EntityNameResolver interface is a contract for resolving the entity name of a given entity instance. The interface defines a single method resolveEntityName which is passed the entity instance and is expected to return the appropriate entity name (null is allowed and would indicate that the resolver does not know how to resolve the entity name of the given entity instance). Generally speaking, an org.hibernate.EntityNameResolver is going to be most useful in the case of dynamic models. One example might be using proxied interfaces as your domain model. The hibernate test suite has an example of this exact style of usage under the org.hibernate.test.dynamicentity.tuplizer2. Here is some of the code from that package for illustration.

/**
 * A very trivial JDK Proxy InvocationHandler implementation where we proxy an interface as
 * the domain model and simply store persistent state in an internal Map.  This is an extremely
 * trivial example meant only for illustration.
 */
public final class DataProxyHandler implements InvocationHandler {
        private String entityName;
        private HashMap data = new HashMap();

        public DataProxyHandler(String entityName, Serializable id) {
                this.entityName = entityName;
                data.put( "Id", id );
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                if ( methodName.startsWith( "set" ) ) {
                        String propertyName = methodName.substring( 3 );
                        data.put( propertyName, args[0] );
                }
                else if ( methodName.startsWith( "get" ) ) {
                        String propertyName = methodName.substring( 3 );
                        return data.get( propertyName );
                }
                else if ( "toString".equals( methodName ) ) {
                        return entityName + "#" + data.get( "Id" );
                }
                else if ( "hashCode".equals( methodName ) ) {
                        return new Integer( this.hashCode() );
                }
                return null;
        }

        public String getEntityName() {
                return entityName;
        }

        public HashMap getData() {
                return data;
        }
}

/**
 *
 */
public class ProxyHelper {
    public static String extractEntityName(Object object) {
        // Our custom java.lang.reflect.Proxy instances actually bundle
        // their appropriate entity name, so we simply extract it from there
        // if this represents one of our proxies; otherwise, we return null
        if ( Proxy.isProxyClass( object.getClass() ) ) {
            InvocationHandler handler = Proxy.getInvocationHandler( object );
            if ( DataProxyHandler.class.isAssignableFrom( handler.getClass() ) ) {
                DataProxyHandler myHandler = ( DataProxyHandler ) handler;
                return myHandler.getEntityName();
            }
        }
        return null;
    }

    // various other utility methods ....

}

/**
 * The EntityNameResolver implementation.
 * IMPL NOTE : An EntityNameResolver really defines a strategy for how entity names should be
 * resolved.  Since this particular impl can handle resolution for all of our entities we want to
 * take advantage of the fact that SessionFactoryImpl keeps these in a Set so that we only ever
 * have one instance registered.  Why?  Well, when it comes time to resolve an entity name,
 * Hibernate must iterate over all the registered resolvers.  So keeping that number down
 * helps that process be as speedy as possible.  Hence the equals and hashCode impls
 */
public class MyEntityNameResolver implements EntityNameResolver {
    public static final MyEntityNameResolver INSTANCE = new MyEntityNameResolver();

    public String resolveEntityName(Object entity) {
        return ProxyHelper.extractEntityName( entity );
    }

    public boolean equals(Object obj) {
        return getClass().equals( obj.getClass() );
    }

    public int hashCode() {
        return getClass().hashCode();
    }
}

public class MyEntityTuplizer extends PojoEntityTuplizer {
        public MyEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
                super( entityMetamodel, mappedEntity );
        }

        public EntityNameResolver[] getEntityNameResolvers() {
                return new EntityNameResolver[] { MyEntityNameResolver.INSTANCE };
        }

    public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory) {
        String entityName = ProxyHelper.extractEntityName( entityInstance );
        if ( entityName == null ) {
            entityName = super.determineConcreteSubclassEntityName( entityInstance, factory );
        }
        return entityName;
    }

    ...
}
        

In order to register an org.hibernate.EntityNameResolver users must either:

  1. Implement a custom Tuplizer, implementing the getEntityNameResolvers method.

  2. Register it with the org.hibernate.impl.SessionFactoryImpl (which is the implementation class fororg.hibernate.SessionFactory) using the registerEntityNameResolver method.

Object/relational mappings are usually defined in an XML document. The mapping document is designed to be readable and hand-editable. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations and not table declarations.

Please note that even though many Hibernate users choose to write the XML by hand, a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA.

Here is an example mapping:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="eg">

        <class name="Cat"
            table="cats"
            discriminator-value="C">

                <id name="id">
                        <generator class="native"/>
                </id>

                <discriminator column="subclass"
                     type="character"/>

                <property name="weight"/>

                <property name="birthdate"
                    type="date"
                    not-null="true"
                    update="false"/>

                <property name="color"
                    type="eg.types.ColorUserType"
                    not-null="true"
                    update="false"/>

                <property name="sex"
                    not-null="true"
                    update="false"/>

                <property name="litterId"
                    column="litterId"
                    update="false"/>

                <many-to-one name="mother"
                    column="mother_id"
                    update="false"/>

                <set name="kittens"
                    inverse="true"
                    order-by="litter_id">
                        <key column="mother_id"/>
                        <one-to-many class="Cat"/>
                </set>

                <subclass name="DomesticCat"
                    discriminator-value="D">

                        <property name="name"
                            type="string"/>

                </subclass>

        </class>

        <class name="Dog">
                <!-- mapping for Dog could go here -->
        </class>

</hibernate-mapping>

We will now discuss the content of the mapping document. We will only describe, however, the document elements and attributes that are used by Hibernate at runtime. The mapping document also contains some extra optional attributes and elements that affect the database schemas exported by the schema export tool (for example, the not-null attribute).

All XML mappings should declare the doctype shown. The actual DTD can be found at the URL above, in the directory hibernate-x.x.x/src/org/hibernate , or in hibernate3.jar. Hibernate will always look for the DTD in its classpath first. If you experience lookups of the DTD using an Internet connection, check the DTD declaration against the contents of your classpath.

This element has several optional attributes. The schema and catalog attributes specify that tables referred to in this mapping belong to the named schema and/or catalog. If they are specified, tablenames will be qualified by the given schema and catalog names. If they are missing, tablenames will be unqualified. The default-cascade attribute specifies what cascade style should be assumed for properties and collections that do not specify a cascade attribute. By default, the auto-import attribute allows you to use unqualified class names in the query language.

<hibernate-mapping
         schema="schemaName"                          (1)
         catalog="catalogName"                        (2)
         default-cascade="cascade_style"              (3)
         default-access="field|property|ClassName"    (4)
         default-lazy="true|false"                    (5)
         auto-import="true|false"                     (6)
         package="package.name"                       (7)
 />
1

schema (optional): the name of a database schema.

2

catalog (optional): the name of a database catalog.

3

default-cascade (optional - defaults to none): a default cascade style.

4

default-access (optional - defaults to property): the strategy Hibernate should use for accessing all properties. It can be a custom implementation of PropertyAccessor.

5

default-lazy (optional - defaults to true): the default value for unspecified lazy attributes of class and collection mappings.

6

auto-import (optional - defaults to true): specifies whether we can use unqualified class names of classes in this mapping in the query language.

7

package (optional): specifies a package prefix to use for unqualified class names in the mapping document.

If you have two persistent classes with the same unqualified name, you should set auto-import="false". An exception will result if you attempt to assign two classes to the same "imported" name.

The hibernate-mapping element allows you to nest several persistent <class> mappings, as shown above. It is, however, good practice (and expected by some tools) to map only a single persistent class, or a single class hierarchy, in one mapping file and name it after the persistent superclass. For example,Cat.hbm.xmlDog.hbm.xml, or if using inheritance, Animal.hbm.xml.

You can declare a persistent class using the class element. For example:

<class
        name="ClassName"                              (1)
        table="tableName"                             (2)
        discriminator-value="discriminator_value"     (3)
        mutable="true|false"                          (4)
        schema="owner"                                (5)
        catalog="catalog"                             (6)
        proxy="ProxyInterface"                        (7)
        dynamic-update="true|false"                   (8)
        dynamic-insert="true|false"                   (9)
        select-before-update="true|false"             (10)
        polymorphism="implicit|explicit"              (11)
        where="arbitrary sql where condition"         (12)
        persister="PersisterClass"                    (13)
        batch-size="N"                                (14)
        optimistic-lock="none|version|dirty|all"      (15)
        lazy="true|false"                             (16)
        entity-name="EntityName"                      (17)
        check="arbitrary sql check condition"         (18)
        rowid="rowid"                                 (19)
        subselect="SQL expression"                    (20)
        abstract="true|false"                         (21)
        node="element-name"
/>
1

name (optional): the fully qualified Java class name of the persistent class or interface. If this attribute is missing, it is assumed that the mapping is for a non-POJO entity.

2

table (optional - defaults to the unqualified class name): the name of its database table.

3

discriminator-value (optional - defaults to the class name): a value that distinguishes individual subclasses that is used for polymorphic behavior. Acceptable values include null and not null.

4

mutable (optional - defaults to true): specifies that instances of the class are (not) mutable.

5

schema (optional): overrides the schema name specified by the root <hibernate-mapping>element.

6

catalog (optional): overrides the catalog name specified by the root <hibernate-mapping>element.

7

proxy (optional): specifies an interface to use for lazy initializing proxies. You can specify the name of the class itself.

8

dynamic-update (optional - defaults to false): specifies that UPDATE SQL should be generated at runtime and can contain only those columns whose values have changed.

9

dynamic-insert (optional - defaults to false): specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

10

select-before-update (optional - defaults to false): specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. Only when a transient object has been associated with a new session using update(), will Hibernate perform an extra SQL SELECT to determine if an UPDATE is actually required.

11

polymorphism (optional - defaults to implicit): determines whether implicit or explicit query polymorphism is used.

12

where (optional): specifies an arbitrary SQL WHERE condition to be used when retrieving objects of this class.

13

persister (optional): specifies a custom ClassPersister.

14

batch-size (optional - defaults to 1): specifies a "batch size" for fetching instances of this class by identifier.

15

optimistic-lock (optional - defaults to version): determines the optimistic locking strategy.

(16)

lazy (optional): lazy fetching can be disabled by setting lazy="false".

(17)

entity-name (optional - defaults to the class name): Hibernate3 allows a class to be mapped multiple times, potentially to different tables. It also allows entity mappings that are represented by Maps or XML at the Java level. In these cases, you should provide an explicit arbitrary name for the entity. See 4.4절. “동적인 모형들” and 18장. XML 매핑 for more information.

(18)

check (optional): an SQL expression used to generate a multi-row check constraint for automatic schema generation.

(19)

rowid (optional): Hibernate can use ROWIDs on databases. On Oracle, for example, Hibernate can use the rowid extra column for fast updates once this option has been set to rowid. A ROWID is an implementation detail and represents the physical location of a stored tuple.

(20)

subselect (optional): maps an immutable and read-only entity to a database subselect. This is useful if you want to have a view instead of a base table. See below for more information.

(21)

abstract (optional): is used to mark abstract superclasses in <union-subclass> hierarchies.

It is acceptable for the named persistent class to be an interface. You can declare implementing classes of that interface using the <subclass> element. You can persist any static inner class. Specify the class name using the standard form i.e. e.g.Foo$Bar.

Immutable classes, mutable="false", cannot be updated or deleted by the application. This allows Hibernate to make some minor performance optimizations.

The optional proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies that implement the named interface. The persistent object will load when a method of the proxy is invoked. See "Initializing collections and proxies" below.

Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or class, and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphism means that class instances will be returned only by queries that explicitly name that class. Queries that name the class will return only instances of subclasses mapped inside this <class> declaration as a <subclass> or <joined-subclass>. For most purposes, the default polymorphism="implicit" is appropriate. Explicit polymorphism is useful when two different classes are mapped to the same table This allows a "lightweight" class that contains a subset of the table columns.

The persister attribute lets you customize the persistence strategy used for the class. You can, for example, specify your own subclass of org.hibernate.persister.EntityPersister, or you can even provide a completely new implementation of the interface org.hibernate.persister.ClassPersister that implements, for example, persistence via stored procedure calls, serialization to flat files or LDAP. Seeorg.hibernate.test.CustomPersister for a simple example of "persistence" to a Hashtable.

The dynamic-update and dynamic-insert settings are not inherited by subclasses, so they can also be specified on the <subclass> or <joined-subclass> elements. Although these settings can increase performance in some cases, they can actually decrease performance in others.

Use of select-before-update will usually decrease performance. It is useful to prevent a database update trigger being called unnecessarily if you reattach a graph of detached instances to a Session.

dynamic-update를 사용가능하게 할 경우, 당신은 다음 optimistic 잠금 전략들을 선택하게 될 것이다:

It is strongly recommended that you use version/timestamp columns for optimistic locking with Hibernate. This strategy optimizes performance and correctly handles modifications made to detached instances (i.e. when Session.merge() is used).

There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level, although some DBMS do not support views properly, especially with updates. Sometimes you want to use a view, but you cannot create one in the database (i.e. with a legacy schema). In this case, you can map an immutable and read-only entity to a given SQL subselect expression:

<class name="Summary">
    <subselect>
        select item.name, max(bid.amount), count(*)
        from item
        join bid on bid.item_id = item.id
        group by item.name
    </subselect>
    <synchronize table="item"/>
    <synchronize table="bid"/>
    <id name="name"/>
    ...
</class>

Declare the tables to synchronize this entity with, ensuring that auto-flush happens correctly and that queries against the derived entity do not return stale data. The <subselect> is available both as an attribute and a nested mapping element.

매핑된 클래스들은 데이터베이스 테이블의 프라이머리 키 컬럼을 선언해야 한다. 대부분의 클래스들은 또한 인스턴스의 유일 식별자를 소유하는 자바빈즈-스타일 프로퍼티를 가질 것이다. <id> 요소는 그 프로퍼티로부터 프라이머리 키 컬럼으로의 매핑을 정의한다.

<id
        name="propertyName"                                          (1)
        type="typename"                                              (2)
        column="column_name"                                         (3)
        unsaved-value="null|any|none|undefined|id_value"             (4)
        access="field|property|ClassName">                           (5)
        node="element-name|@attribute-name|element/@attribute|."

        <generator class="generatorClass"/>
</id>
1

name (optional): the name of the identifier property.

2

type (옵션): Hibernate 타입을 나타내는 이름.

3

column (optional - defaults to the property name): the name of the primary key column.

4

unsaved-value (optional - defaults to a "sensible" value): an identifier property value that indicates an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session.

5

access (optional - defaults to property): the strategy Hibernate should use for accessing the property value.

name 속성이 누락되면, 클래스는 식별자 프로퍼티를 갖지 않는다고 가정된다.

unsaved-value 속성은 Hibernate3에서는 거의 필요하지 않다.

There is an alternative <composite-id> declaration that allows access to legacy data with composite keys. Its use is strongly discouraged for anything else.

선택적인 <generator> 자식 요소는 영속 클래스의 인스턴스들에 대한 유일 식별자들을 생성시키는데 사용되는 자바 클래스를 명명한다. 만일 임의의 파라미터들이 생성기 인스턴스를 구성하거나 초기화 시키는데 필요할 경우, 그것들은<param> 요소 를 사용하여 전달된다.

<id name="id" type="long" column="cat_id">
        <generator class="org.hibernate.id.TableHiLoGenerator">
                <param name="table">uid_table</param>
                <param name="column">next_hi_value_column</param>
        </generator>
</id>

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

동일한 테이블 속으로 데이터를 입력하는 다른 프로세스가 없을 때에만 유일한 longshort 또는 int 타입의 식별자들을 생성시킨다. 클러스터 내에서는 사용하지 말라.

identity

DB2, MySQL, MS SQL Server, Sybase, HypersonicSQL에서 식별 컬럼들을 지원한다. 반환되는 식별자는 long,short 또는 int 타입이다.

sequence

DB2, PostgreSQL, Oracle, SAP DB, McKoi에서 시퀀스를 사용하거나 Interbase에서 생성기(generator)를 사용한다. 반환되는 식별자는 longshort 또는 int 타입이다.

hilo

테이블과 컬럼(디폴트로 각각 hibernate_unique_key와 next_hi)이 hi 값들의 소스로서 주어지면, longshort 또는int 타입의 식별자들을 효과적으로 생성시키는데 hi/lo 알고리즘을 사용한다. hi/lo 알고리즘은 특정 데이터베이스에 대해서만 유일한 식별자들을 생성시킨다.

seqhilo

명명된 데이터베이스 시퀀스가 주어지면, longshort 또는 int 타입의 식별자들을 효과적으로 생성시키는데 hi/lo 알고리즘을 사용한다.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

MS SQL Server와 MySQL 상에서 데이터베이스 생성 GUID 문자열을 사용한다.

native

selects identitysequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a <one-to-one>primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

Starting with release 3.2.3, there are 2 new generators which represent a re-thinking of 2 different aspects of identifier generation. The first aspect is database portability; the second is optimization Optimization means that you do not have to query the database for every request for a new identifier value. These two new generators are intended to take the place of some of the named generators described above, starting in 3.3.x. However, they are included in the current releases and can be referenced by FQN.

The first of these new generators is org.hibernate.id.enhanced.SequenceStyleGenerator which is intended, firstly, as a replacement for the sequence generator and, secondly, as a better portability generator thannative. This is because native generally chooses between identity and sequence which have largely different semantics that can cause subtle issues in applications eyeing portability.org.hibernate.id.enhanced.SequenceStyleGenerator, however, achieves portability in a different manner. It chooses between a table or a sequence in the database to store its incrementing values, depending on the capabilities of the dialect being used. The difference between this and native is that table-based and sequence-based storage have the same exact semantic. In fact, sequences are exactly what Hibernate tries to emulate with its table-based generators. This generator has a number of configuration parameters:

The second of these new generators is org.hibernate.id.enhanced.TableGenerator, which is intended, firstly, as a replacement for the table generator, even though it actually functions much more likeorg.hibernate.id.MultipleHiLoPerTableGenerator, and secondly, as a re-implementation oforg.hibernate.id.MultipleHiLoPerTableGenerator that utilizes the notion of pluggable optimizers. Essentially this generator defines a table capable of holding a number of different increment values simultaneously by using multiple distinctly keyed rows. This generator has a number of configuration parameters:

  • table_name (optional - defaults to hibernate_sequences): the name of the table to be used.

  • value_column_name (optional - defaults to next_val): the name of the column on the table that is used to hold the value.

  • segment_column_name (optional - defaults to sequence_name): the name of the column on the table that is used to hold the "segment key". This is the value which identifies which increment value to use.

  • segment_value (optional - defaults to default): The "segment key" value for the segment from which we want to pull increment values for this generator.

  • segment_value_length (optional - defaults to 255): Used for schema generation; the column size to create this segment key column.

  • initial_value (optional - defaults to 1): The initial value to be retrieved from the table.

  • increment_size (optional - defaults to 1): The value by which subsequent calls to the table should differ.

  • optimizer (optional - defaults to ): See 5.1.6절. “NOT TRANSLATED! Identifier generator optimization”

For identifier generators that store values in the database, it is inefficient for them to hit the database on each and every call to generate a new identifier value. Instead, you can group a bunch of them in memory and only hit the database when you have exhausted your in-memory value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators (5.1.5절. “NOT TRANSLATED!Enhanced identifier generators” support this operation.

  • none (generally this is the default if no optimizer was specified): this will not perform any optimizations and hit the database for each and every request.

  • hilo: applies a hi/lo algorithm around the database retrieved values. The values from the database for this optimizer are expected to be sequential. The values retrieved from the database structure for this optimizer indicates the "group number". The increment_size is multiplied by that value in memory to define a group "hi value".

  • pooled: as with the case of hilo, this optimizer attempts to minimize the number of hits to the database. Here, however, we simply store the starting value for the "next group" into the database structure rather than a sequential value in combination with an in-memory grouping algorithm. Here, increment_size refers to the values coming from the database.

<composite-id name="propertyName" class="ClassName" mapped="true|false" access="field|property|ClassName"> node="element-name|." <key-property name="propertyName" type="typename" column="column_name"/> <key-many-to-one name="propertyName class="ClassName" column="column_name"/> ...... </composite-id>

A table with a composite key can be mapped with multiple properties of the class as identifier properties. The <composite-id> element accepts <key-property> property mappings and <key-many-to-one> mappings as child elements.

<composite-id> <key-property name="medicareNumber"/> <key-property name="dependent"/> </composite-id>

The persistent class must override equals() and hashCode() to implement composite identifier equality. It must also implement Serializable.

Unfortunately, this approach means that a persistent object is its own identifier. There is no convenient "handle" other than the object itself. You must instantiate an instance of the persistent class itself and populate its identifier properties before you can load() the persistent state associated with a composite key. We call this approach an embedded composite identifier, and discourage it for serious applications.

두 번째 접근법은 우리가 mapped composite 식별자라고 부르는 것인데, 여기서 <composite-id> 요소 내에 명명된 여기서 식별자 프로퍼티들은 영속 클래스와 별도의 식별자 클래스 양자 상에 중복된다.

<composite-id class="MedicareId" mapped="true"> <key-property name="medicareNumber"/> <key-property name="dependent"/> </composite-id>

In this example, both the composite identifier class, MedicareId, and the entity class itself have properties named medicareNumber and dependent. The identifier class must override equals() and hashCode() and implement Serializable. The main disadvantage of this approach is code duplication.

다음 속성들은 매핑된 composite 식별자를 지정하는데 사용된다:

  • mapped (optional - defaults to false): indicates that a mapped composite identifier is used, and that the contained property mappings refer to both the entity class and the composite identifier class.

  • class (optional - but required for a mapped composite identifier): the class used as a composite identifier.

We will describe a third, even more convenient approach, where the composite identifier is implemented as a component class in 8.4절. “composite 식별자들로서 컴포넌트들”. The attributes described below apply only to this alternative approach:

  • name (optional - required for this approach): a property of component type that holds the composite identifier. Please see chapter 9 for more information.

  • access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

  • class (optional - defaults to the property type determined by reflection): the component class used as a composite identifier. Please see the next section for more information.

The third approach, an identifier component, is recommended for almost all applications.

The <discriminator> element is required for polymorphic persistence using the table-per-class-hierarchy mapping strategy. It declares a discriminator column of the table. The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. A restricted set of types can be used: stringcharacterintegerbyteshortbooleanyes_notrue_false.

<discriminator column="discriminator_column" (1)type="discriminator_type" (2)force="true|false" (3)insert="true|false" (4)formula="arbitrary sql expression" (5)/>
1

column (optional - defaults to class): the name of the discriminator column.

2

type (optional - defaults to string): a name that indicates the Hibernate type

3

force (optional - defaults to false): "forces" Hibernate to specify the allowed discriminator values, even when retrieving all instances of the root class.

4

insert (optional - defaults to true): set this to false if your discriminator column is also part of a mapped composite identifier. It tells Hibernate not to include the column in SQL INSERTs.

5

formula (optional): an arbitrary SQL expression that is executed when a type has to be evaluated. It allows content-based discrimination.

discriminator 컬럼의 실제 값들은 <class> 요소와 <subclass> 요소의 discriminator-value 속성에 의해 지정된다.

The force attribute is only useful if the table contains rows with "extra" discriminator values that are not mapped to a persistent class. This will not usually be the case.

The formula attribute allows you to declare an arbitrary SQL expression that will be used to evaluate the type of a row. For example:

<discriminator formula="case when CLASS_TYPE in ('a', 'b', 'c') then 0 else 1 end" type="integer"/>

The <version> element is optional and indicates that the table contains versioned data. This is particularly useful if you plan to use long transactions. See below for more information:

<version column="version_column" (1)name="propertyName" (2)type="typename" (3)access="field|property|ClassName" (4)unsaved-value="null|negative|undefined" (5)generated="never|always" (6)insert="true|false" (7)node="element-name|@attribute-name|element/@attribute|." />
1

column (optional - defaults to the property name): the name of the column holding the version number.

2

name: the name of a property of the persistent class.

3

type (optional - defaults to integer): the type of the version number.

4

access (optional - defaults to property): the strategy Hibernate uses to access the property value.

5

unsaved-value (optional - defaults to undefined): a version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. Undefined specifies that the identifier property value should be used.

6

generated (optional - defaults to never): specifies that this version property value is generated by the database. See the discussion of generated properties for more information.

7

insert (optional - defaults to true): specifies whether the version column should be included in SQL insert statements. It can be set to false if the database column is defined with a default value of0.

Version numbers can be of Hibernate type longintegershorttimestamp or calendar.

A version or timestamp property should never be null for a detached instance. Hibernate will detect any instance with a null version or timestamp as transient, irrespective of what other unsaved-value strategies are specified. Declaring a nullable version or timestamp property is an easy way to avoid problems with transitive reattachment in Hibernate. It is especially useful for people using assigned identifiers or composite keys.

The optional <timestamp> element indicates that the table contains timestamped data. This provides an alternative to versioning. Timestamps are a less safe implementation of optimistic locking. However, sometimes the application might use the timestamps in other ways.

<timestamp column="timestamp_column" (1)name="propertyName" (2)access="field|property|ClassName" (3)unsaved-value="null|undefined" (4)source="vm|db" (5)generated="never|always" (6)node="element-name|@attribute-name|element/@attribute|." />
1

column (optional - defaults to the property name): the name of a column holding the timestamp.

2

name: the name of a JavaBeans style property of Java type Date or Timestamp of the persistent class.

3

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

4

unsaved-value (optional - defaults to null): a version property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. Undefined specifies that the identifier property value should be used.

5

source (optional - defaults to vm): Where should Hibernate retrieve the timestamp value from? From the database, or from the current JVM? Database-based timestamps incur an overhead because Hibernate must hit the database in order to determine the "next value". It is safer to use in clustered environments. Not all Dialects are known to support the retrieval of the database's current timestamp. Others may also be unsafe for usage in locking due to lack of precision (Oracle 8, for example).

6

generated (optional - defaults to never): specifies that this timestamp property value is actually generated by the database. See the discussion of generated properties for more information.

The <property> element declares a persistent JavaBean style property of the class.

<property name="propertyName" (1)column="column_name" (2)type="typename" (3)update="true|false" (4)insert="true|false" (4)formula="arbitrary SQL expression" (5)access="field|property|ClassName" (6)lazy="true|false" (7)unique="true|false" (8)not-null="true|false" (9)optimistic-lock="true|false" (10)generated="never|insert|always" (11)node="element-name|@attribute-name|element/@attribute|." index="index_name" unique_key="unique_key_id" length="L" precision="P" scale="S" />
1

name: 첫 소문자로 시작하는 프로퍼티 이름.

2

column (optional - defaults to the property name): the name of the mapped database table column. This can also be specified by nested <column> element(s).

3

type (옵션): Hibernate 타입을 나타내는 이름.

4

update, insert (optional - defaults to true): specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" property whose value is initialized from some other property that maps to the same column(s), or by a trigger or other application.

5

formula (옵션): 계산되는 프로퍼티에 대해 값을 정의하는 SQL 표현식. 계산되는 프로퍼티들은 그것들 자신에 대한 컬럼 매핑을 갖지 않는다.

6

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

7

lazy (optional - defaults to false): specifies that this property should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation.

8

unique (optional): enables the DDL generation of a unique constraint for the columns. Also, allow this to be the target of a property-ref.

9

not-null (optional): enables the DDL generation of a nullability constraint for the columns.

10

optimistic-lock (optional - defaults to true): specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, it determines if a version increment should occur when this property is dirty.

11

generated (optional - defaults to never): specifies that this property value is actually generated by the database. See the discussion of generated properties for more information.

typename은 다음일 수 있다:

  1. The name of a Hibernate basic type: integer, string, character, date, timestamp, float, binary, serializable, object, blob etc.

  2. The name of a Java class with a default basic type: int, float, char, java.lang.String, java.util.Date, java.lang.Integer, java.sql.Clob etc.

  3. serializable Java 클래스의 이름.

  4. The class name of a custom type: com.illflow.type.MyCustomType etc.

If you do not specify a type, Hibernate will use reflection upon the named property and guess the correct Hibernate type. Hibernate will attempt to interpret the name of the return class of the property getter using, in order, rules 2, 3, and 4. In certain cases you will need the type attribute. For example, to distinguish between Hibernate.DATE and Hibernate.TIMESTAMP, or to specify a custom type.

The access attribute allows you to control how Hibernate accesses the property at runtime. By default, Hibernate will call the property get/set pair. If you specify access="field", Hibernate will bypass the get/set pair and access the field directly using reflection. You can specify your own strategy for property access by naming a class that implements the interface org.hibernate.property.PropertyAccessor.

A powerful feature is derived properties. These properties are by definition read-only. The property value is computed at load time. You declare the computation as an SQL expression. This then translates to a SELECT clause subquery in the SQL query that loads an instance:

<property name="totalPrice" formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p WHERE li.productId = p.productId AND li.customerId = customerId AND li.orderNumber = orderNumber )"/>

You can reference the entity table by not declaring an alias on a particular column. This would be customerId in the given example. You can also use the nested <formula> mapping element if you do not want to use the attribute.

An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association; a foreign key in one table is referencing the primary key column(s) of the target table.

<many-to-one name="propertyName" (1)column="column_name" (2)class="ClassName" (3)cascade="cascade_style" (4)fetch="join|select" (5)update="true|false" (6)insert="true|false" (6)property-ref="propertyNameFromAssociatedClass" (7)access="field|property|ClassName" (8)unique="true|false" (9)not-null="true|false" (10)optimistic-lock="true|false" (11)lazy="proxy|no-proxy|false" (12)not-found="ignore|exception" (13)entity-name="EntityName" (14)formula="arbitrary SQL expression" (15)node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" index="index_name" unique_key="unique_key_id" foreign-key="foreign_key_name" />
1

name: the name of the property.

2

column (optional): the name of the foreign key column. This can also be specified by nested<column> element(s).

3

class (optional - defaults to the property type determined by reflection): the name of the associated class.

4

cascade (optional): specifies which operations should be cascaded from the parent object to the associated object.

5

fetch (optional - defaults to select): chooses between outer-join fetching or sequential select fetching.

6

update, insert (optional - defaults to true): specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized from another property that maps to the same column(s), or by a trigger or other application.

7

property-ref (optional): the name of a property of the associated class that is joined to this foreign key. If not specified, the primary key of the associated class is used.

8

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

9

unique (optional): enables the DDL generation of a unique constraint for the foreign-key column. By allowing this to be the target of a property-ref, you can make the association multiplicity one-to-one.

10

not-null (optional): enables the DDL generation of a nullability constraint for the foreign key columns.

11

optimistic-lock (optional - defaults to true): specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, it determines if a version increment should occur when this property is dirty.

12

lazy (optional - defaults to proxy): by default, single point associations are proxied.lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed. This requires build-time bytecode instrumentation. lazy="false" specifies that the association will always be eagerly fetched.

13

not-found (optional - defaults to exception): specifies how foreign keys that reference missing rows will be handled. ignore will treat a missing row as a null association.

14

entity-name (optional): the entity name of the associated class.

15

formula (옵션): 계산된 foreign key에 대한 값을 정의하는 SQL 표현식.

Setting a value of the cascade attribute to any meaningful value other than none will propagate certain operations to the associated object. The meaningful values are divided into three categories. First, basic operations, which include: persist, merge, delete, save-update, evict, replicate, lock and refresh; second, special values: delete-orphan; and third,all comma-separated combinations of operation names: cascade="persist,merge,evict" or cascade="all,delete-orphan". See 10.11절. “Transitive persistence(전이 영속)” for a full explanation. Note that single valued, many-to-one and one-to-one, associations do not support orphan delete.

Here is an example of a typical many-to-one declaration:

<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

The property-ref attribute should only be used for mapping legacy data where a foreign key refers to a unique key of the associated table other than the primary key. This is a complicated and confusing relational model. For example, if the Product class had a unique serial number that is not the primary key. The unique attribute controls Hibernate's DDL generation with the SchemaExport tool.

<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>

그런 다음 OrderItem에 대한 매핑은 다음을 사용할 것이다:

<many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/>

This is not encouraged, however.

만일 참조된 유일 키가 연관된 엔티티의 여러 프로퍼티들을 포함할 경우, 당신은 명명된 <properties> 요소 내부에 참조된 프로퍼티들을 매핑할 것이다.

If the referenced unique key is the property of a component, you can specify a property path:

<many-to-one name="owner" property-ref="identity.ssn" column="OWNER_SSN"/>

또 다른 영속 클래스에 대한 one-to-one 연관관계는 one-to-one 요소를 사용하여 선언된다.

<one-to-one name="propertyName" (1)class="ClassName" (2)cascade="cascade_style" (3)constrained="true|false" (4)fetch="join|select" (5)property-ref="propertyNameFromAssociatedClass" (6)access="field|property|ClassName" (7)formula="any SQL expression" (8)lazy="proxy|no-proxy|false" (9)entity-name="EntityName" (10)node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" foreign-key="foreign_key_name" />
1

name: the name of the property.

2

class (optional - defaults to the property type determined by reflection): the name of the associated class.

3

cascade (optional): specifies which operations should be cascaded from the parent object to the associated object.

4

constrained (optional): specifies that a foreign key constraint on the primary key of the mapped table and references the table of the associated class. This option affects the order in whichsave() and delete() are cascaded, and determines whether the association can be proxied. It is also used by the schema export tool.

5

fetch (optional - defaults to select): chooses between outer-join fetching or sequential select fetching.

6

property-ref (optional): the name of a property of the associated class that is joined to the primary key of this class. If not specified, the primary key of the associated class is used.

7

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

8

formula (optional): almost all one-to-one associations map to the primary key of the owning entity. If this is not the case, you can specify another column, columns or expression to join on using an SQL formula. See org.hibernate.test.onetooneformula for an example.

9

lazy (optional - defaults to proxy): by default, single point associations are proxied.lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation. lazy="false" specifies that the association will always be eagerly fetched. Note that if constrained="false", proxying is impossible and Hibernate will eagerly fetch the association.

10

entity-name (optional): the entity name of the associated class.

There are two varieties of one-to-one associations:

  • 프라이머리 키 연관관계들

  • 유일 foreign 키 연관관계들

Primary key associations do not need an extra table column. If two rows are related by the association, then the two table rows share the same primary key value. To relate two objects by a primary key association, ensure that they are assigned the same identifier value.

For a primary key association, add the following mappings to Employee and Person respectively:

<one-to-one name="person" class="Person"/>
<one-to-one name="employee" class="Employee" constrained="true"/>

Ensure that the primary keys of the related rows in the PERSON and EMPLOYEE tables are equal. You use a special Hibernate identifier generation strategy called foreign:

<class name="person" table="PERSON"> <id name="id" column="PERSON_ID"> <generator class="foreign"> <param name="property">employee</param> </generator> </id> ... <one-to-one name="employee" class="Employee" constrained="true"/> </class>

A newly saved instance of Person is assigned the same primary key value as the Employee instance referred with the employee property of that Person.

Alternatively, a foreign key with a unique constraint, from Employee to Person, can be expressed as:

<many-to-one name="person" class="Person" column="PERSON_ID" unique="true"/>

This association can be made bidirectional by adding the following to the Person mapping:

<one-to-one name="employee" class="Employee" property-ref="person"/>
<natural-id mutable="true|false"/> <property ... /> <many-to-one ... /> ...... </natural-id>

Although we recommend the use of surrogate keys as primary keys, you should try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. It is also immutable. Map the properties of the natural key inside the <natural-id> element. Hibernate will generate the necessary unique key and nullability constraints and, as a result, your mapping will be more self-documenting.

It is recommended that you implement equals() and hashCode() to compare the natural key properties of the entity.

This mapping is not intended for use with entities that have natural primary keys.

  • mutable (optional - defaults to false): by default, natural identifier properties are assumed to be immutable (constant).

The <component> element maps properties of a child object to columns of the table of a parent class. Components can, in turn, declare their own properties, components or collections. See the "Component" examples below:

<component name="propertyName" (1)class="className" (2)insert="true|false" (3)update="true|false" (4)access="field|property|ClassName" (5)lazy="true|false" (6)optimistic-lock="true|false" (7)unique="true|false" (8)node="element-name|." > <property ...../> <many-to-one .... /> ........ </component>
1

name: the name of the property.

2

class (optional - defaults to the property type determined by reflection): the name of the component (child) class.

3

insert: do the mapped columns appear in SQL INSERTs?

4

update: do the mapped columns appear in SQL UPDATEs?

5

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

6

lazy (optional - defaults to false): specifies that this component should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation.

7

optimistic-lock (optional - defaults to true): specifies that updates to this component either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when this property is dirty.

8

unique (optional - defaults to false): specifies that a unique constraint exists upon all mapped columns of the component.

자식 <property> 태그들은 자식 클래스의 프로퍼티들을 테이블 컬럼들로 매핑시킨다.

<component> 요소는 컴포넌트 클래스의 프로퍼티를 포함하는 엔티티에 대한 참조로서 매핑시키는 <parent> 서브요소를 허용한다.

The <dynamic-component> element allows a Map to be mapped as a component, where the property names refer to keys of the map. See 8.5절. “동적인 컴포넌트들” for more information.

The <properties> element allows the definition of a named, logical grouping of the properties of a class. The most important use of the construct is that it allows a combination of properties to be the target of a property-ref. It is also a convenient way to define a multi-column unique constraint. For example:

<properties name="logicalName" (1)insert="true|false" (2)update="true|false" (3)optimistic-lock="true|false" (4)unique="true|false" (5)> <property ...../> <many-to-one .... /> ........ </properties>
1

name: the logical name of the grouping. It is not an actual property name.

2

insert: do the mapped columns appear in SQL INSERTs?

3

update: do the mapped columns appear in SQL UPDATEs?

4

optimistic-lock (optional - defaults to true): specifies that updates to these properties either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when these properties are dirty.

5

unique (optional - defaults to false): specifies that a unique constraint exists upon all mapped columns of the component.

예를 들어, 만일 우리가 다음 <properties> 매핑을 가질 경우:

<class name="Person"> <id name="personNumber"/> ... <properties name="name" unique="true" update="false"> <property name="firstName"/> <property name="initial"/> <property name="lastName"/> </properties> </class>

You might have some legacy data association that refers to this unique key of the Person table, instead of to the primary key:

<many-to-one name="person" class="Person" property-ref="name"> <column name="firstName"/> <column name="initial"/> <column name="lastName"/> </many-to-one>

The use of this outside the context of mapping legacy data is not recommended.

Polymorphic persistence requires the declaration of each subclass of the root persistent class. For the table-per-class-hierarchy mapping strategy, the <subclass> declaration is used. For example:

<subclass name="ClassName" (1)discriminator-value="discriminator_value" (2)proxy="ProxyInterface" (3)lazy="true|false" (4)dynamic-update="true|false" dynamic-insert="true|false" entity-name="EntityName" node="element-name" extends="SuperclassName"> <property .... /> ..... </subclass>
1

name: the fully qualified class name of the subclass.

2

discriminator-value (optional - defaults to the class name): a value that distinguishes individual subclasses.

3

proxy (optional): specifies a class or interface used for lazy initializing proxies.

4

lazy (optional - defaults to true): setting lazy="false" disables the use of lazy fetching.

Each subclass declares its own persistent properties and subclasses. <version> and <id> properties are assumed to be inherited from the root class. Each subclass in a hierarchy must define a unique discriminator-value. If this is not specified, the fully qualified Java class name is used.

For information about inheritance mappings see 9장. Inheritance mapping.

Each subclass can also be mapped to its own table. This is called the table-per-subclass mapping strategy. An inherited state is retrieved by joining with the table of the superclass. To do this you use the <joined-subclass> element. For example:

<joined-subclass name="ClassName" (1)table="tablename" (2)proxy="ProxyInterface" (3)lazy="true|false" (4)dynamic-update="true|false" dynamic-insert="true|false" schema="schema" catalog="catalog" extends="SuperclassName" persister="ClassName" subselect="SQL expression" entity-name="EntityName" node="element-name"> <key .... > <property .... /> ..... </joined-subclass>
1

name: the fully qualified class name of the subclass.

2

table: the name of the subclass table.

3

proxy (optional): specifies a class or interface to use for lazy initializing proxies.

4

lazy (optional, defaults to true): setting lazy="false" disables the use of lazy fetching.

A discriminator column is not required for this mapping strategy. Each subclass must, however, declare a table column holding the object identifier using the <key> element. The mapping at the start of the chapter would then be re-written as:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="eg"> <class name="Cat" table="CATS"> <id name="id" column="uid" type="long"> <generator class="hilo"/> </id> <property name="birthdate" type="date"/> <property name="color" not-null="true"/> <property name="sex" not-null="true"/> <property name="weight"/> <many-to-one name="mate"/> <set name="kittens"> <key column="MOTHER"/> <one-to-many class="Cat"/> </set> <joined-subclass name="DomesticCat" table="DOMESTIC_CATS"> <key column="CAT"/> <property name="name" type="string"/> </joined-subclass> </class> <class name="eg.Dog"> <!-- mapping for Dog could go here --> </class> </hibernate-mapping>

For information about inheritance mappings see 9장. Inheritance mapping.

A third option is to map only the concrete classes of an inheritance hierarchy to tables. This is called the table-per-concrete-class strategy. Each table defines all persistent states of the class, including the inherited state. In Hibernate, it is not necessary to explicitly map such inheritance hierarchies. You can map each class with a separate <class> declaration. However, if you wish use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the <union-subclass> mapping. For example:

<union-subclass name="ClassName" (1)table="tablename" (2)proxy="ProxyInterface" (3)lazy="true|false" (4)dynamic-update="true|false" dynamic-insert="true|false" schema="schema" catalog="catalog" extends="SuperclassName" abstract="true|false" persister="ClassName" subselect="SQL expression" entity-name="EntityName" node="element-name"> <property .... /> ..... </union-subclass>
1

name: the fully qualified class name of the subclass.

2

table: the name of the subclass table.

3

proxy (optional): specifies a class or interface to use for lazy initializing proxies.

4

lazy (optional, defaults to true): setting lazy="false" disables the use of lazy fetching.

이 매핑 방도에는 판별자 컬럼이나 키 컬럼이 필요하지 않다.

For information about inheritance mappings see 9장. Inheritance mapping.

Using the <join> element, it is possible to map properties of one class to several tables that have a one-to-one relationship. For example:

<join table="tablename" (1)schema="owner" (2)catalog="catalog" (3)fetch="join|select" (4)inverse="true|false" (5)optional="true|false"> (6)<key ... /> <property ... /> ... </join>
1

table: the name of the joined table.

2

schema (optional): overrides the schema name specified by the root <hibernate-mapping> element.

3

catalog (optional): overrides the catalog name specified by the root <hibernate-mapping> element.

4

fetch (optional - defaults to join): if set to join, the default, Hibernate will use an inner join to retrieve a <join> defined by a class or its superclasses. It will use an outer join for a <join>defined by a subclass. If set to select then Hibernate will use a sequential select for a <join>defined on a subclass. This will be issued only if a row represents an instance of the subclass. Inner joins will still be used to retrieve a <join> defined by the class and its superclasses.

5

inverse (optional - defaults to false): if enabled, Hibernate will not insert or update the properties defined by this join.

6

optional (optional - defaults to false): if enabled, Hibernate will insert a row only if the properties defined by this join are non-null. It will always use an outer join to retrieve the properties.

For example, address information for a person can be mapped to a separate table while preserving value type semantics for all properties:

<class name="Person" table="PERSON"> <id name="id" column="PERSON_ID">...</id> <join table="ADDRESS"> <key column="ADDRESS_ID"/> <property name="address"/> <property name="zip"/> <property name="country"/> </join> ...

This feature is often only useful for legacy data models. We recommend fewer tables than classes and a fine-grained domain model. However, it is useful for switching between inheritance mapping strategies in a single hierarchy, as explained later.

The <key> element has featured a few times within this guide. It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table. It also defines the foreign key in the joined table:

<key column="columnname" (1)on-delete="noaction|cascade" (2)property-ref="propertyName" (3)not-null="true|false" (4)update="true|false" (5)unique="true|false" (6)/>
1

column (optional): the name of the foreign key column. This can also be specified by nested<column> element(s).

2

on-delete (optional - defaults to noaction): specifies whether the foreign key constraint has database-level cascade delete enabled.

3

property-ref (optional): specifies that the foreign key refers to columns that are not the primary key of the original table. It is provided for legacy data.

4

not-null (optional): specifies that the foreign key columns are not nullable. This is implied whenever the foreign key is also part of the primary key.

5

update (optional): specifies that the foreign key should never be updated. This is implied whenever the foreign key is also part of the primary key.

6

unique (optional): specifies that the foreign key should have a unique constraint. This is implied whenever the foreign key is also the primary key.

For systems where delete performance is important, we recommend that all keys should be defined on-delete="cascade". Hibernate uses a database-level ON CASCADE DELETE constraint, instead of many individual DELETE statements. Be aware that this feature bypasses Hibernate's usual optimistic locking strategy for versioned data.

The not-null and update attributes are useful when mapping a unidirectional one-to-many association. If you map a unidirectional one-to-many association to a non-nullable foreign key, you must declare the key column using <key not-null="true">.

Mapping elements which accept a column attribute will alternatively accept a <column> subelement. Likewise, <formula> is an alternative to the formula attribute. For example:

<column name="column_name" length="N" precision="N" scale="N" not-null="true|false" unique="true|false" unique-key="multicolumn_unique_key_name" index="index_name" sql-type="sql_type_name" check="SQL expression" default="SQL expression"/>
<formula>SQL expression</formula>

column and formula attributes can even be combined within the same property or association mapping to express, for example, exotic join conditions.

<many-to-one name="homeAddress" class="Address" insert="false" update="false"> <column name="person_id" not-null="true" length="10"/> <formula>'MAILING'</formula> </many-to-one>

If your application has two persistent classes with the same name, and you do not want to specify the fully qualified package name in Hibernate queries, classes can be "imported" explicitly, rather than relying upon auto-import="true". You can also import classes and interfaces that are not explicitly mapped:

<import class="java.lang.Object" rename="Universe"/>
<import class="ClassName" (1)rename="ShortName" (2)/>
1

class: the fully qualified class name of any Java class.

2

rename (optional - defaults to the unqualified class name): a name that can be used in the query language.

There is one more type of property mapping. The <any> mapping element defines a polymorphic association to classes from multiple tables. This type of mapping requires more than one column. The first column contains the type of the associated entity. The remaining columns contain the identifier. It is impossible to specify a foreign key constraint for this kind of association. This is not the usual way of mapping polymorphic associations and you should use this only in special cases. For example, for audit logs, user session data, etc.

The meta-type attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by id-type. You must specify the mapping from values of the meta-type to class names.

<any name="being" id-type="long" meta-type="string"> <meta-value value="TBL_ANIMAL" class="Animal"/> <meta-value value="TBL_HUMAN" class="Human"/> <meta-value value="TBL_ALIEN" class="Alien"/> <column name="table_name"/> <column name="id"/> </any>
<any name="propertyName" (1)id-type="idtypename" (2)meta-type="metatypename" (3)cascade="cascade_style" (4)access="field|property|ClassName" (5)optimistic-lock="true|false" (6)> <meta-value ... /> <meta-value ... /> ..... <column .... /> <column .... /> ..... </any>
1

name: 프로퍼티 이름.

2

id-type: 식별자 타입.

3

meta-type (optional - defaults to string): any type that is allowed for a discriminator mapping.

4

cascade (optional- defaults to none): cascade 스타일.

5

access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.

6

optimistic-lock (optional - defaults to true): specifies that updates to this property either do or do not require acquisition of the optimistic lock. It defines whether a version increment should occur if this property is dirty.

In relation to the persistence service, Java language-level objects are classified into two groups:

An entity exists independently of any other objects holding references to the entity. Contrast this with the usual Java model, where an unreferenced object is garbage collected. Entities must be explicitly saved and deleted. Saves and deletions, however, can be cascaded from a parent entity to its children. This is different from the ODMG model of object persistence by reachability and corresponds more closely to how application objects are usually used in large systems. Entities support circular and shared references. They can also be versioned.

An entity's persistent state consists of references to other entities and instances of value types. Values are primitives: collections (not what is inside a collection), components and certain immutable objects. Unlike entities, values in particular collections and components, are persisted and deleted by reachability. Since value objects and primitives are persisted and deleted along with their containing entity, they cannot be independently versioned. Values have no independent identity, so they cannot be shared by two entities or collections.

Until now, we have been using the term "persistent class" to refer to entities. We will continue to do that. Not all user-defined classes with a persistent state, however, are entities. A component is a user-defined class with value semantics. A Java property of type java.lang.String also has value semantics. Given this definition, all types (classes) provided by the JDK have value type semantics in Java, while user-defined types can be mapped with entity or value type semantics. This decision is up to the application developer. An entity class in a domain model will normally have shared references to a single instance of that class, while composition or aggregation usually translates to a value type.

We will revisit both concepts throughout this reference guide.

The challenge is to map the Java type system, and the developers' definition of entities and value types, to the SQL/database type system. The bridge between both systems is provided by Hibernate. For entities, <class><subclass> and so on are used. For value types we use <property><component>etc., that usually have a type attribute. The value of this attribute is the name of a Hibernate mapping type. Hibernate provides a range of mappings for standard JDK value types out of the box. You can write your own mapping types and implement your own custom conversion strategies.

With the exception of collections, all built-in Hibernate types support null semantics.

The built-in basic mapping types can be roughly categorized into the following:

integer, long, short, float, double, character, byte, boolean, yes_no, true_false

자바 원시타입들이나 wrapper 클래스들로부터 적절한(벤더-지정적인) SQL 컬럼 타입들로의 타입 매핑. boolean, yes_no와 true_false는 Java boolean이나 java.lang.Boolean에 대한 모든 대체적인 인코딩들이다.

string

java.lang.String으로부터 VARCHAR (또는 Oracle VARCHAR2)로의 타입 매핑.

date, time, timestamp

java.util.Date와 그것의 서브클래스로부터 SQL 타입들인 DATETIMETIMESTAMP (또는 등가물)로의 타입 매핑들.

calendar, calendar_date

java.util.Calendar로부터 SQL 타입들인 TIMESTAMPDATE (또는 등가물)로의 타입 매핑들.

big_decimal, big_integer

java.math.BigDecimal과 java.math.BigInteger로부터 NUMERIC (또는 Oracle NUMBER)로의 타입 매핑들.

locale, timezone, currency

java.util.Localejava.util.TimeZone, 그리고 java.util.Currency로부터 VARCHAR(또는 Oracle VARCHAR2)로의 타입 매핑. Locale과 Currency의 인스턴스들은 그것들의 ISO 코드들로 매핑된다. TimeZone의 인스턴스들은 그것들의 ID로 매핑된다.

class

java.lang.Class로부터 VARCHAR (또는 Oracle VARCHAR2)로의 타입 매핑. Class는 그것의 전체 수식어가 붙은 이름으로 매핑된다.

binary

byte 배열들을 적절한 SQL binary 타입으로 매핑시킨다.

text

long Java 문자열을 SQL CLOB 또는 TEXT 타입으로 매핑시킨다

serializable

Maps serializable Java types to an appropriate SQL binary type. You can also indicate the Hibernate type serializable with the name of a serializable Java class or interface that does not default to a basic type.

clob, blob

Type mappings for the JDBC classes java.sql.Clob and java.sql.Blob. These types can be inconvenient for some applications, since the blob or clob object cannot be reused outside of a transaction. Driver support is patchy and inconsistent.

imm_date, imm_time, imm_timestamp, imm_calendar, imm_calendar_date, imm_serializable, imm_binary

Type mappings for what are considered mutable Java types. This is where Hibernate makes certain optimizations appropriate only for immutable Java types, and the application treats the object as immutable. For example, you should not call Date.setTime() for an instance mapped as imm_timestamp. To change the value of the property, and have that change made persistent, the application must assign a new, nonidentical, object to the property.

Unique identifiers of entities and collections can be of any basic type except binaryblob and clob. Composite identifiers are also allowed. See below for more information.

기본 value 타입들은 org.hibernate.Hibernate에 정의되어 있는 대응하는 Type 상수들을 갖는다. 예를 들어, Hibernate.STRING은 string 타입을 표현한다.

It is relatively easy for developers to create their own value types. For example, you might want to persist properties of type java.lang.BigInteger to VARCHAR columns. Hibernate does not provide a built-in type for this. Custom types are not limited to mapping a property, or collection element, to a single table column. So, for example, you might have a Java property getName()/setName() of type java.lang.String that is persisted to the columns FIRST_NAMEINITIALSURNAME.

To implement a custom type, implement either org.hibernate.UserType or org.hibernate.CompositeUserType and declare properties using the fully qualified classname of the type. View org.hibernate.test.DoubleStringType to see the kind of things that are possible.

<property name="twoStrings" type="org.hibernate.test.DoubleStringType"> <column name="first_string"/> <column name="second_string"/> </property>

하나의 프로퍼티를 여러 개의 컬럼들로 매핑시키는 <column> 태그의 사용을 주목하라.

CompositeUserTypeEnhancedUserTypeUserCollectionType, 그리고 UserVersionType 인터페이스들은 더 많은 특화된 사용들을 위한 지원을 제공한다.

You can even supply parameters to a UserType in the mapping file. To do this, your UserType must implement the org.hibernate.usertype.ParameterizedType interface. To supply parameters to your custom type, you can use the <type> element in your mapping files.

<property name="priority"> <type name="com.mycompany.usertypes.DefaultValueIntegerType"> <param name="default">0</param> </type> </property>

UserType은 이제 그것에 전달된 Properties 객체로부터 default로 명명된 파라미터에 대한 값을 검색할 수 있다.

If you regularly use a certain UserType, it is useful to define a shorter name for it. You can do this using the <typedef> element. Typedefs assign a name to a custom type, and can also contain a list of default parameter values if the type is parameterized.

<typedef class="com.mycompany.usertypes.DefaultValueIntegerType" name="default_zero"> <param name="default">0</param> </typedef>
<property name="priority" type="default_zero"/>

property 매핑 상에 type 파라미터들을 사용함으로써 경우에 맞게 typedef 내에 제공된 파라미터들을 오버라이드 시키는 것이 가능하다.

Even though Hibernate's rich range of built-in types and support for components means you will rarely need to use a custom type, it is considered good practice to use custom types for non-entity classes that occur frequently in your application. For example, a MonetaryAmount class is a good candidate for a CompositeUserType, even though it could be mapped as a component. One reason for this is abstraction. With a custom type, your mapping documents would be protected against changes to the way monetary values are represented.

It is possible to provide more than one mapping for a particular persistent class. In this case, you must specify an entity name to disambiguate between instances of the two mapped entities. By default, the entity name is the same as the class name. Hibernate lets you specify the entity name when working with persistent objects, when writing queries, or when mapping associations to the named entity.

<class name="Contract" table="Contracts" entity-name="CurrentContract"> ... <set name="history" inverse="true" order-by="effectiveEndDate desc"> <key column="currentContractId"/> <one-to-many entity-name="HistoricalContract"/> </set> </class> <class name="Contract" table="ContractHistory" entity-name="HistoricalContract"> ... <many-to-one name="currentContract" column="currentContractId" entity-name="CurrentContract"/> </class>

Associations are now specified using entity-name instead of class.

You can force Hibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document. Hibernate will use the correct quotation style for the SQL Dialect. This is usually double quotes, but the SQL Server uses brackets and MySQL uses backticks.

<class name="LineItem" table="`Line Item`"> <id name="id" column="`Item Id`"/><generator class="assigned"/></id> <property name="itemNumber" column="`Item #`"/> ... </class>

XML does not suit all users so there are some alternative ways to define O/R mapping metadata in Hibernate.

Many Hibernate users prefer to embed mapping information directly in sourcecode using XDoclet @hibernate.tags. We do not cover this approach in this reference guide since it is considered part of XDoclet. However, we include the following example of the Cat class with XDoclet mappings:

package eg; import java.util.Set; import java.util.Date; /** * @hibernate.class * table="CATS" */ public class Cat { private Long id; // identifier private Date birthdate; private Cat mother; private Set kittens private Color color; private char sex; private float weight; /* * @hibernate.id * generator-class="native" * column="CAT_ID" */ public Long getId() { return id; } private void setId(Long id) { this.id=id; } /** * @hibernate.many-to-one * column="PARENT_ID" */ public Cat getMother() { return mother; } void setMother(Cat mother) { this.mother = mother; } /** * @hibernate.property * column="BIRTH_DATE" */ public Date getBirthdate() { return birthdate; } void setBirthdate(Date date) { birthdate = date; } /** * @hibernate.property * column="WEIGHT" */ public float getWeight() { return weight; } void setWeight(float weight) { this.weight = weight; } /** * @hibernate.property * column="COLOR" * not-null="true" */ public Color getColor() { return color; } void setColor(Color color) { this.color = color; } /** * @hibernate.set * inverse="true" * order-by="BIRTH_DATE" * @hibernate.collection-key * column="PARENT_ID" * @hibernate.collection-one-to-many */ public Set getKittens() { return kittens; } void setKittens(Set kittens) { this.kittens = kittens; } // addKitten not needed by Hibernate public void addKitten(Cat kitten) { kittens.add(kitten); } /** * @hibernate.property * column="SEX" * not-null="true" * update="false" */ public char getSex() { return sex; } void setSex(char sex) { this.sex=sex; } }

See the Hibernate website for more examples of XDoclet and Hibernate.

JDK 5.0 introduced XDoclet-style annotations at the language level that are type-safe and checked at compile time. This mechanism is more powerful than XDoclet annotations and better supported by tools and IDEs. IntelliJ IDEA, for example, supports auto-completion and syntax highlighting of JDK 5.0 annotations. The new revision of the EJB specification (JSR-220) uses JDK 5.0 annotations as the primary metadata mechanism for entity beans. Hibernate3 implements the EntityManager of JSR-220 (the persistence API). Support for mapping metadata is available via the Hibernate Annotations package as a separate download. Both EJB3 (JSR-220) and Hibernate3 metadata is supported.

다음은 EJB 엔티티 빈으로서 주석이 붙은 POJO 클래스에 관한 예제이다:

@Entity(access = AccessType.FIELD) public class Customer implements Serializable { @Id; Long id; String firstName; String lastName; Date birthday; @Transient Integer age; @Embedded private Address homeAddress; @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="CUSTOMER_ID") Set<Order> orders; // Getter/setter and business methods }

Generated properties are properties that have their values generated by the database. Typically, Hibernate applications needed to refresh objects that contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. When Hibernate issues an SQL INSERT or UPDATE for an entity that has defined generated properties, it immediately issues a select afterwards to retrieve the generated values.

Properties marked as generated must additionally be non-insertable and non-updateable. Only versionstimestamps, and simple properties, can be marked as generated.

never (the default): the given property value is not generated within the database.

insert: the given property value is generated on insert, but is not regenerated on subsequent updates. Properties like created-date fall into this category. Even though version and timestamp properties can be marked as generated, this option is not available.

always: the property value is generated both on insert and on update.

Auxiliary database objects allow for the CREATE and DROP of arbitrary database objects. In conjunction with Hibernate's schema evolution tools, they have the ability to fully define a user schema within the Hibernate mapping files. Although designed specifically for creating and dropping things like triggers or stored procedures, any SQL command that can be run via a java.sql.Statement.execute() method is valid (for example, ALTERs, INSERTS, etc.). There are essentially two modes for defining auxiliary database objects:

The first mode is to explicitly list the CREATE and DROP commands in the mapping file:

<hibernate-mapping> ... <database-object> <create>CREATE TRIGGER my_trigger ...</create> <drop>DROP TRIGGER my_trigger</drop> </database-object> </hibernate-mapping>

The second mode is to supply a custom class that constructs the CREATE and DROP commands. This custom class must implement the org.hibernate.mapping.AuxiliaryDatabaseObject interface.

<hibernate-mapping> ... <database-object> <definition class="MyTriggerDefinition"/> </database-object> </hibernate-mapping>

Additionally, these database objects can be optionally scoped so that they only apply when certain dialects are used.

<hibernate-mapping> ... <database-object> <definition class="MyTriggerDefinition"/> <dialect-scope name="org.hibernate.dialect.Oracle9iDialect"/> <dialect-scope name="org.hibernate.dialect.Oracle10gDialect"/> </database-object> </hibernate-mapping>

Hibernate requires that persistent collection-valued fields be declared as an interface type. For example:

public class Product { private String serialNumber; private Set parts = new HashSet(); public Set getParts() { return parts; } void setParts(Set parts) { this.parts = parts; } public String getSerialNumber() { return serialNumber; } void setSerialNumber(String sn) { serialNumber = sn; } }

The actual interface might be java.util.Setjava.util.Collectionjava.util.Listjava.util.Mapjava.util.SortedSetjava.util.SortedMap or anything you like ("anything you like" means you will have to write an implementation of org.hibernate.usertype.UserCollectionType.)

Notice how the instance variable was initialized with an instance of HashSet. This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances. When you make the instance persistent, by calling persist() for example, Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set. Be aware of the following errors:

Cat cat = new DomesticCat(); Cat kitten = new DomesticCat(); .... Set kittens = new HashSet(); kittens.add(kitten); cat.setKittens(kittens); session.persist(cat); kittens = cat.getKittens(); // Okay, kittens collection is a Set (HashSet) cat.getKittens(); // Error!

The persistent collections injected by Hibernate behave like HashMapHashSetTreeMapTreeSet or ArrayList, depending on the interface type.

Collections instances have the usual behavior of value types. They are automatically persisted when referenced by a persistent object and are automatically deleted when unreferenced. If a collection is passed from one persistent object to another, its elements might be moved from one table to another. Two entities cannot share a reference to the same collection instance. Due to the underlying relational model, collection-valued properties do not support null value semantics. Hibernate does not distinguish between a null collection reference and an empty collection.

Use persistent collections the same way you use ordinary Java collections. However, please ensure you understand the semantics of bidirectional associations (these are discussed later).

The Hibernate mapping element used for mapping a collection depends upon the type of interface. For example, a <set> element is used for mapping properties of type Set.

<class name="Product"> <id name="serialNumber" column="productSerialNumber"/> <set name="parts"> <key column="productSerialNumber" not-null="true"/> <one-to-many class="Part"/> </set> </class>

<set>과는 별도로, 또한 <list><map><bag><array>, 그리고 <map> 매핑 요소들이 존재한다. <map> 요소가 대표적이다:

<map name="propertyName" (1)table="table_name" (2)schema="schema_name" (3)lazy="true|extra|false" (4)inverse="true|false" (5)cascade="all|none|save-update|delete|all-delete-orphan|delet(6)e-orphan" sort="unsorted|natural|comparatorClass" (7)order-by="column_name asc|desc" (8)where="arbitrary sql where condition" (9)fetch="join|select|subselect" (10)batch-size="N" (11)access="field|property|ClassName" (12)optimistic-lock="true|false" (13)mutable="true|false" (14)node="element-name|." embed-xml="true|false" > <key .... /> <map-key .... /> <element .... /> </map>
1

name: the collection property name

2

table (optional - defaults to property name): the name of the collection table. It is not used for one-to-many associations.

3

schema (optional): the name of a table schema to override the schema declared on the root element

4

lazy (optional - defaults to true): disables lazy fetching and specifies that the association is always eagerly fetched. It can also be used to enable "extra-lazy" fetching where most operations do not initialize the collection. This is suitable for large collections.

5

inverse (optional - defaults to false): marks this collection as the "inverse" end of a bidirectional association.

6

cascade (optional - defaults to none): enables operations to cascade to child entities.

7

sort (optional): specifies a sorted collection with natural sort order or a given comparator class.

8

order-by (optional, JDK1.4 only): specifies a table column or columns that define the iteration order of the MapSet or bag, together with an optional asc or desc.

9

where (optional): specifies an arbitrary SQL WHERE condition that is used when retrieving or removing the collection. This is useful if the collection needs to contain only a subset of the available data.

10

fetch (optional, defaults to select): chooses between outer-join fetching, fetching by sequential select, and fetching by sequential subselect.

11

batch-size (optional, defaults to 1): specifies a "batch size" for lazily fetching instances of this collection.

12

access (optional - defaults to property): the strategy Hibernate uses for accessing the collection property value.

13

optimistic-lock (optional - defaults to true): specifies that changes to the state of the collection results in increments of the owning entity's version. For one-to-many associations you may want to disable this setting.

14

mutable (optional - defaults to true): a value of false specifies that the elements of the collection never change. This allows for minor performance optimization in some cases.

Collection instances are distinguished in the database by the foreign key of the entity that owns the collection. This foreign key is referred to as the collection key column, or columns, of the collection table. The collection key column is mapped by the <key> element.

There can be a nullability constraint on the foreign key column. For most collections, this is implied. For unidirectional one-to-many associations, the foreign key column is nullable by default, so you may need to specify not-null="true".

<key column="productSerialNumber" not-null="true"/>

The foreign key constraint can use ON DELETE CASCADE.

<key column="productSerialNumber" on-delete="cascade"/>

<key> 요소에 대한 전체 정의는 앞 장을 보라.

Collections can contain almost any other Hibernate type, including: basic types, custom types, components and references to other entities. This is an important distinction. An object in a collection might be handled with "value" semantics (its life cycle fully depends on the collection owner), or it might be a reference to another entity with its own life cycle. In the latter case, only the "link" between the two objects is considered to be a state held by the collection.

포함된 타입은 콜렉션 요소 타입으로서 불려진다. 콜렉션 요소들은 <element> 또는 <composite-element>에 의해 매핑되거나, 엔티티 참조들의 경우에 <one-to-many> 또는 <many-to-many>로서 매핑된다. 앞의 두 개는 value 의미를 가진 요소들을 매핑시키고, 뒤의 두개는 엔티티 연관들을 매핑하는데 사용된다.

All collection mappings, except those with set and bag semantics, need an index column in the collection table. An index column is a column that maps to an array index, or List index, or Map key. The index of a Map may be of any basic type, mapped with <map-key>. It can be an entity reference mapped with <map-key-many-to-many>, or it can be a composite type mapped with <composite-map-key>. The index of an array or list is always of type integer and is mapped using the <list-index> element. The mapped column contains sequential integers that are numbered from zero by default.

<list-index column="column_name" (1)base="0|1|..."/>
1

column_name (required): the name of the column holding the collection index values.

1

base (optional - defaults to 0): the value of the index column that corresponds to the first element of the list or array.

<map-key column="column_name" (1)formula="any SQL expression" (2)type="type_name" (3)node="@attribute-name" length="N"/>
1

column (optional): the name of the column holding the collection index values.

2

formula (optional): a SQL formula used to evaluate the key of the map.

3

type (required): the type of the map keys.

<map-key-many-to-many column="column_name" (1)formula="any SQL expression" (2)(3)class="ClassName" />
1

column (optional): the name of the foreign key column for the collection index values.

2

formula (optional): a SQ formula used to evaluate the foreign key of the map key.

3

class (required): the entity class used as the map key.

If your table does not have an index column, and you still wish to use List as the property type, you can map the property as a Hibernate <bag>. A bag does not retain its order when it is retrieved from the database, but it can be optionally sorted or ordered.

Any collection of values or many-to-many associations requires a dedicated collection table with a foreign key column or columns, collection element column or columns, and possibly an index column or columns.

For a collection of values use the <element> tag. For example:

<element column="column_name" (1)formula="any SQL expression" (2)type="typename" (3)length="L" precision="P" scale="S" not-null="true|false" unique="true|false" node="element-name" />
1

column (optional): the name of the column holding the collection element values.

2

formula (optional): an SQL formula used to evaluate the element.

3

type (required): the type of the collection element.

many-to-many association is specified using the <many-to-many> element.

<many-to-many column="column_name" (1)formula="any SQL expression" (2)class="ClassName" (3)fetch="select|join" (4)unique="true|false" (5)not-found="ignore|exception" (6)entity-name="EntityName" (7)property-ref="propertyNameFromAssociatedClass" (8)node="element-name" embed-xml="true|false" />
1

column (optional): the name of the element foreign key column.

2

formula (optional): an SQL formula used to evaluate the element foreign key value.

3

class (required): the name of the associated class.

4

fetch (optional - defaults to join): enables outer-join or sequential select fetching for this association. This is a special case; for full eager fetching in a single SELECT of an entity and its many-to-many relationships to other entities, you would enable join fetching,not only of the collection itself, but also with this attribute on the <many-to-many> nested element.

5

unique (optional): enables the DDL generation of a unique constraint for the foreign-key column. This makes the association multiplicity effectively one-to-many.

6

not-found (optional - defaults to exception): specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association.

7

entity-name (optional): the entity name of the associated class, as an alternative to class.

8

property-ref (optional): the name of a property of the associated class that is joined to this foreign key. If not specified, the primary key of the associated class is used.

Here are some examples.

A set of strings:

<set name="names" table="person_names"> <key column="person_id"/> <element column="person_name" type="string"/> </set>

A bag containing integers with an iteration order determined by the order-by attribute:

<bag name="sizes" table="item_sizes" order-by="size asc"> <key column="item_id"/> <element column="size" type="integer"/> </bag>

An array of entities, in this case, a many-to-many association:

<array name="addresses" table="PersonAddress" cascade="persist"> <key column="personId"/> <list-index column="sortOrder"/> <many-to-many column="addressId" class="Address"/> </array>

날짜들에 대한 문자열 인덱스들을 가진 map :

<map name="holidays" table="holidays" schema="dbo" order-by="hol_name asc"> <key column="id"/> <map-key column="hol_name" type="string"/> <element column="hol_date" type="date"/> </map>

A list of components (this is discussed in the next chapter):

<list name="carComponents" table="CarComponents"> <key column="carId"/> <list-index column="sortOrder"/> <composite-element class="CarComponent"> <property name="price"/> <property name="type"/> <property name="serialNumber" column="serialNum"/> </composite-element> </list>

one-to-many association links the tables of two classes via a foreign key with no intervening collection table. This mapping loses certain semantics of normal Java collections:

  • An instance of the contained entity class cannot belong to more than one instance of the collection.

  • An instance of the contained entity class cannot appear at more than one value of the collection index.

An association from Product to Part requires the existence of a foreign key column and possibly an index column to the Part table. A <one-to-many> tag indicates that this is a one-to-many association.

<one-to-many class="ClassName" (1)not-found="ignore|exception" (2)entity-name="EntityName" (3)node="element-name" embed-xml="true|false" />
1

class (required): the name of the associated class.

2

not-found (optional - defaults to exception): specifies how cached identifiers that reference missing rows will be handled. ignore will treat a missing row as a null association.

3

entity-name (optional): the entity name of the associated class, as an alternative to class.

The <one-to-many> element does not need to declare any columns. Nor is it necessary to specify the table name anywhere.

The following example shows a map of Part entities by name, where partName is a persistent property of Part. Notice the use of a formula-based index:

<map name="parts" cascade="all"> <key column="productId" not-null="true"/> <map-key formula="partName"/> <one-to-many class="Part"/> </map>

Hibernate는 java.util.SortedMap과 java.util.SortedSet를 구현하는 콜렉션들을 지원한다. 당신은 매핑 파일 속에 하나의 comparator를 지정해야 한다:

<set name="aliases" table="person_aliases" sort="natural"> <key column="person"/> <element column="name" type="string"/> </set> <map name="holidays" sort="my.custom.HolidayComparator"> <key column="year_id"/> <map-key column="hol_name" type="string"/> <element column="hol_date" type="date"/> </map>

sort 속성에 허용되는 값들은 unsortednatural, 그리고 java.util.Comparator를 구현하는 클래스의 이름이다.

Sorted 콜렉션들은 java.util.TreeSet 또는 java.util.TreeMap처럼 행동한다.

If you want the database itself to order the collection elements, use the order-by attribute of setbag or map mappings. This solution is only available under JDK 1.4 or higher and is implemented using LinkedHashSet or LinkedHashMap. This performs the ordering in the SQL query and not in the memory.

<set name="aliases" table="person_aliases" order-by="lower(name) asc"> <key column="person"/> <element column="name" type="string"/> </set> <map name="holidays" order-by="hol_date, hol_name"> <key column="year_id"/> <map-key column="hol_name" type="string"/> <element column="hol_date type="date"/> </map>

Associations can even be sorted by arbitrary criteria at runtime using a collection filter():

sortedUsers = s.createFilter( group.getUsers(), "order by this.name" ).list();

bidirectional association allows navigation from both "ends" of the association. Two kinds of bidirectional association are supported:

one-to-many

set or bag valued at one end and single-valued at the other

many-to-many

양 끝에서 set 또는 bag 값을 가진 연관

You can specify a bidirectional many-to-many association by mapping two many-to-many associations to the same database table and declaring one end as inverse. You cannot select an indexed collection.

Here is an example of a bidirectional many-to-many association that illustrates how each category can have many items and each item can be in many categories:

<class name="Category"> <id name="id" column="CATEGORY_ID"/> ... <bag name="items" table="CATEGORY_ITEM"> <key column="CATEGORY_ID"/> <many-to-many class="Item" column="ITEM_ID"/> </bag> </class> <class name="Item"> <id name="id" column="ITEM_ID"/> ... <!-- inverse end --> <bag name="categories" table="CATEGORY_ITEM" inverse="true"> <key column="ITEM_ID"/> <many-to-many class="Category" column="CATEGORY_ID"/> </bag> </class>

Changes made only to the inverse end of the association are not persisted. This means that Hibernate has two representations in memory for every bidirectional association: one link from A to B and another link from B to A. This is easier to understand if you think about the Java object model and how a many-to-many relationship in Javais created:

category.getItems().add(item); // The category now "knows" about the relationship item.getCategories().add(category); // The item now "knows" about the relationship session.persist(item); // The relationship won't be saved! session.persist(category); // The relationship will be saved

non-inverse 측은 메모리 내 표상을 데이터베이스로 저장하는데 사용된다.

You can define a bidirectional one-to-many association by mapping a one-to-many association to the same table column(s) as a many-to-one association and declaring the many-valued end inverse="true".

<class name="Parent"> <id name="id" column="parent_id"/> .... <set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id" column="child_id"/> .... <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class>

Mapping one end of an association with inverse="true" does not affect the operation of cascades as these are orthogonal concepts.

A bidirectional association where one end is represented as a <list> or <map>, requires special consideration. If there is a property of the child class that maps to the index column you can use inverse="true" on the collection mapping:

<class name="Parent"> <id name="id" column="parent_id"/> .... <map name="children" inverse="true"> <key column="parent_id"/> <map-key column="name" type="string"/> <one-to-many class="Child"/> </map> </class> <class name="Child"> <id name="id" column="child_id"/> .... <property name="name" not-null="true"/> <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class>

If there is no such property on the child class, the association cannot be considered truly bidirectional. That is, there is information available at one end of the association that is not available at the other end. In this case, you cannot map the collection inverse="true". Instead, you could use the following mapping:

<class name="Parent"> <id name="id" column="parent_id"/> .... <map name="children"> <key column="parent_id" not-null="true"/> <map-key column="name" type="string"/> <one-to-many class="Child"/> </map> </class> <class name="Child"> <id name="id" column="child_id"/> .... <many-to-one name="parent" class="Parent" column="parent_id" insert="false" update="false" not-null="true"/> </class>

Note that in this mapping, the collection-valued end of the association is responsible for updates to the foreign key.

There are three possible approaches to mapping a ternary association. One approach is to use a Map with an association as its index:

<map name="contracts"> <key column="employer_id" not-null="true"/> <map-key-many-to-many column="employee_id" class="Employee"/> <one-to-many class="Contract"/> </map>
<map name="connections"> <key column="incoming_node_id"/> <map-key-many-to-many column="outgoing_node_id" class="Node"/> <many-to-many column="connection_id" class="Connection"/> </map>

A second approach is to remodel the association as an entity class. This is the most common approach.

A final alternative is to use composite elements, which will be discussed later.

The majority of the many-to-many associations and collections of values shown previously all map to tables with composite keys, even though it has been have suggested that entities should have synthetic identifiers (surrogate keys). A pure association table does not seem to benefit much from a surrogate key, although a collection of composite values might. It is for this reason that Hibernate provides a feature that allows you to map many-to-many associations and collections of values to a table with a surrogate key.

The <idbag> element lets you map a List (or Collection) with bag semantics. For example:

<idbag name="lovers" table="LOVERS"> <collection-id column="ID" type="long"> <generator class="sequence"/> </collection-id> <key column="PERSON1"/> <many-to-many column="PERSON2" class="Person" fetch="join"/> </idbag>

An <idbag> has a synthetic id generator, just like an entity class. A different surrogate key is assigned to each collection row. Hibernate does not, however, provide any mechanism for discovering the surrogate key value of a particular row.

The update performance of an <idbag> supersedes a regular <bag>. Hibernate can locate individual rows efficiently and update or delete them individually, similar to a list, map or set.

현재 구현에서, native 식별자 생성 방도는 <idbag> 콜렉션 식별자들에 대해 지원되지 않는다.

This section covers collection examples.

The following class has a collection of Child instances:

package eg; import java.util.Set; public class Parent { private long id; private Set children; public long getId() { return id; } private void setId(long id) { this.id=id; } private Set getChildren() { return children; } private void setChildren(Set children) { this.children=children; } .... .... }

If each child has, at most, one parent, the most natural mapping is a one-to-many association:

<hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

이것은 다음 테이블 정의들로 매핑된다:

create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key, name varchar(255), parent_id bigint ) alter table child add constraint childfk0 (parent_id) references parent

만일 부모가 필수적이라면, 양방향 one-to-many 연관관계를 사용하라:

<hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class> </hibernate-mapping>

NOT NULL 컨스트레인트를 주목하라:

create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key, name varchar(255), parent_id bigint not null ) alter table child add constraint childfk0 (parent_id) references parent

Alternatively, if this association must be unidirectional you can declare the NOT NULL constraint on the <key> mapping:

<hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children"> <key column="parent_id" not-null="true"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

On the other hand, if a child has multiple parents, a many-to-many association is appropriate:

<hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" table="childset"> <key column="parent_id"/> <many-to-many class="Child" column="child_id"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping>

테이블 정의들:

create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key, name varchar(255) ) create table childset ( parent_id bigint not null, child_id bigint not null, primary key ( parent_id, child_id ) ) alter table childset add constraint childsetfk0 (parent_id) references parent alter table childset add constraint childsetfk1 (child_id) references child

For more examples and a complete explanation of a parent/child relationship mapping, see 21장. 예제: 부모/자식 for more information.

Even more complex association mappings are covered in the next chapter.

Association mappings are often the most difficult thing to implement correctly. In this section we examine some canonical cases one by one, starting with unidirectional mappings and then bidirectional cases. We will use Person and Address in all the examples.

Associations will be classified by multiplicity and whether or not they map to an intervening join table.

Nullable foreign keys are not considered to be good practice in traditional data modelling, so our examples do not use nullable foreign keys. This is not a requirement of Hibernate, and the mappings will work if you drop the nullability constraints.

bidirectional many-to-one association is the most common kind of association. The following example illustrates the standard parent/child relationship.

<class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class>
create table Person ( personId bigint not null primary key, addressId bigint not null ) create table Address ( addressId bigint not null primary key )

If you use a List, or other indexed collection, set the key column of the foreign key to not null. Hibernate will manage the association from the collections side to maintain the index of each element, making the other side virtually inverse by setting update="false" and insert="false":

<class name="Person"> <id name="id"/> ... <many-to-one name="address" column="addressId" not-null="true" insert="false" update="false"/> </class> <class name="Address"> <id name="id"/> ... <list name="people"> <key column="addressId" not-null="true"/> <list-index column="peopleIdx"/> <one-to-many class="Person"/> </list> </class>

If the underlying foreign key column is NOT NULL, it is important that you define not-null="true" on the <key> element of the collection mapping. Do not only declare not-null="true" on a possible nested <column> element, but on the <key> element.

More complex association joins are extremely rare. Hibernate handles more complex situations by using SQL fragments embedded in the mapping document. For example, if a table with historical account information data defines accountNumbereffectiveEndDate and effectiveStartDatecolumns, it would be mapped as follows:

<properties name="currentAccountKey"> <property name="accountNumber" type="string" not-null="true"/> <property name="currentAccount" type="boolean"> <formula>case when effectiveEndDate is null then 1 else 0 end</formula> </property> </properties> <property name="effectiveEndDate" type="date"/> <property name="effectiveStateDate" type="date" not-null="true"/>

You can then map an association to the current instance, the one with null effectiveEndDate, by using:

<many-to-one name="currentAccountInfo" property-ref="currentAccountKey" class="AccountInfo"> <column name="accountNumber"/> <formula>'1'</formula> </many-to-one>

In a more complex example, imagine that the association between Employee and Organization is maintained in an Employment table full of historical employment data. An association to the employee's most recent employer, the one with the most recent startDate, could be mapped in the following way:

<join> <key column="employeeId"/> <subselect> select employeeId, orgId from Employments group by orgId having startDate = max(startDate) </subselect> <many-to-one name="mostRecentEmployer" class="Organization" column="orgId"/> </join>

This functionality allows a degree of creativity and flexibility, but it is more practical to handle these kinds of cases using HQL or a criteria query.

The notion of a component is re-used in several different contexts and purposes throughout Hibernate.

A component is a contained object that is persisted as a value type and not an entity reference. The term "component" refers to the object-oriented notion of composition and not to architecture-level components. For example, you can model a person like this:

public class Person { private java.util.Date birthday; private Name name; private String key; public String getKey() { return key; } private void setKey(String key) { this.key=key; } public java.util.Date getBirthday() { return birthday; } public void setBirthday(java.util.Date birthday) { this.birthday = birthday; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } ...... ...... }
public class Name { char initial; String first; String last; public String getFirst() { return first; } void setFirst(String first) { this.first = first; } public String getLast() { return last; } void setLast(String last) { this.last = last; } public char getInitial() { return initial; } void setInitial(char initial) { this.initial = initial; } }

Now Name can be persisted as a component of PersonName defines getter and setter methods for its persistent properties, but it does not need to declare any interfaces or identifier properties.

Our Hibernate mapping would look like this:

<class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg.Name"> <!-- class attribute optional --> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class>

person 테이블은 pidbirthdayinitialfirstlast 컬럼들을 가질 것이다.

Like value types, components do not support shared references. In other words, two persons could have the same name, but the two person objects would contain two independent name objects that were only "the same" by value. The null value semantics of a component are ad hoc. When reloading the containing object, Hibernate will assume that if all component columns are null, then the entire component is null. This is suitable for most purposes.

The properties of a component can be of any Hibernate type (collections, many-to-one associations, other components, etc). Nested components should not be considered an exotic usage. Hibernate is intended to support a fine-grained object model.

<component> 요소는 컴포넌트 클래스의 프로퍼티를 포함되는 엔티티에 대한 역 참조로서 매핑시키는 <parent> 서브요소를 허용한다.

<class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg.Name" unique="true"> <parent name="namedPerson"/> <!-- reference back to the Person --> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class>

Collections of components are supported (e.g. an array of type Name). Declare your component collection by replacing the <element> tag with a <composite-element> tag:

<set name="someNames" table="some_names" lazy="true"> <key column="id"/> <composite-element class="eg.Name"> <!-- class attribute required --> <property name="initial"/> <property name="first"/> <property name="last"/> </composite-element> </set>

Composite elements can contain components but not collections. If your composite element contains components, use the <nested-composite-element> tag. This case is a collection of components which themselves have components. You may want to consider if a one-to-many association is more appropriate. Remodel the composite element as an entity, but be aware that even though the Java model is the same, the relational model and persistence semantics are still slightly different.

A composite element mapping does not support null-able properties if you are using a <set>. There is no separate primary key column in the composite element table. Hibernate uses each column's value to identify a record when deleting objects, which is not possible with null values. You have to either use only not-null properties in a composite-element or choose a <list><map><bag> or <idbag>.

A special case of a composite element is a composite element with a nested <many-to-one> element. This mapping allows you to map extra columns of a many-to-many association table to the composite element class. The following is a many-to-many association from Order to Item, where purchaseDateprice and quantity are properties of the association:

<class name="eg.Order" .... > .... <set name="purchasedItems" table="purchase_items" lazy="true"> <key column="order_id"> <composite-element class="eg.Purchase"> <property name="purchaseDate"/> <property name="price"/> <property name="quantity"/> <many-to-one name="item" class="eg.Item"/> <!-- class attribute is optional --> </composite-element> </set> </class>

There cannot be a reference to the purchase on the other side for bidirectional association navigation. Components are value types and do not allow shared references. A single Purchase can be in the set of an Order, but it cannot be referenced by the Item at the same time.

심지어 세겹의(또는 네 겹의, 기타) 연관들이 가능하다:

<class name="eg.Order" .... > .... <set name="purchasedItems" table="purchase_items" lazy="true"> <key column="order_id"> <composite-element class="eg.OrderLine"> <many-to-one name="purchaseDetails class="eg.Purchase"/> <many-to-one name="item" class="eg.Item"/> </composite-element> </set> </class>

Composite elements can appear in queries using the same syntax as associations to other entities.

The <composite-map-key> element allows you to map a component class as the key of a Map. Ensure that you override hashCode() and equals() correctly on the component class.

You can use a component as an identifier of an entity class. Your component class must satisfy certain requirements:

  • 그것은 java.io.Serializable을 구현해야 한다.

  • It must re-implement equals() and hashCode() consistently with the database's notion of composite key equality.

You cannot use an IdentifierGenerator to generate composite keys. Instead the application must assign its own identifiers.

Use the <composite-id> tag, with nested <key-property> elements, in place of the usual <id> declaration. For example, the OrderLine class has a primary key that depends upon the (composite) primary key of Order.

<class name="OrderLine"> <composite-id name="id" class="OrderLineId"> <key-property name="lineId"/> <key-property name="orderId"/> <key-property name="customerId"/> </composite-id> <property name="name"/> <many-to-one name="order" class="Order" insert="false" update="false"> <column name="orderId"/> <column name="customerId"/> </many-to-one> .... </class>

Any foreign keys referencing the OrderLine table are now composite. Declare this in your mappings for other classes. An association to OrderLine is mapped like this:

<many-to-one name="orderLine" class="OrderLine"> <!-- the "class" attribute is optional, as usual --> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </many-to-one>

OrderLine에 대한 many-to-many 연관은 또한 composite foreign 키를 사용한다:

<set name="undeliveredOrderLines"> <key column name="warehouseId"/> <many-to-many class="OrderLine"> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </many-to-many> </set>

Order에서 OrderLine들의 콜렉션이 사용될 것이다:

<set name="orderLines" inverse="true"> <key> <column name="orderId"/> <column name="customerId"/> </key> <one-to-many class="OrderLine"/> </set>

The <one-to-many> element declares no columns.

만일 OrderLine 자체가 하나의 콜렉션을 소유할 경우, 그것은 또한 하나의 composite foreign 키를 갖는다.

<class name="OrderLine"> .... .... <list name="deliveryAttempts"> <key> <!-- a collection inherits the composite key type --> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </key> <list-index column="attemptId" base="1"/> <composite-element class="DeliveryAttempt"> ... </composite-element> </set> </class>

You can also map a property of type Map:

<dynamic-component name="userAttributes"> <property name="foo" column="FOO" type="string"/> <property name="bar" column="BAR" type="integer"/> <many-to-one name="baz" class="Baz" column="BAZ_ID"/> </dynamic-component>

The semantics of a <dynamic-component> mapping are identical to <component>. The advantage of this kind of mapping is the ability to determine the actual properties of the bean at deployment time just by editing the mapping document. Runtime manipulation of the mapping document is also possible, using a DOM parser. You can also access, and change, Hibernate's configuration-time metamodel via the Configuration object.

Hibernate는 세 가지 기본적인 상속 매핑 방도들을 지원한다:

  • table per class hierarchy

  • table per subclass

  • table per concrete class

게다가 Hibernate는 네 번째의 약간 다른 종류의 다형성을 지원한다:

  • implicit polymorphism(함축적인 다형성)

It is possible to use different mapping strategies for different branches of the same inheritance hierarchy. You can then make use of implicit polymorphism to achieve polymorphism across the whole hierarchy. However, Hibernate does not support mixing <subclass><joined-subclass> and <union-subclass> mappings under the same root <class> element. It is possible to mix together the table per hierarchy and table per subclass strategies under the the same <class> element, by combining the <subclass> and <join> elements (see below for an example).

It is possible to define subclassunion-subclass, and joined-subclass mappings in separate mapping documents directly beneath hibernate-mapping. This allows you to extend a class hierarchy by adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming a previously mapped superclass. Previously this feature made the ordering of the mapping documents important. Since Hibernate3, the ordering of mapping files is irrelevant when using the extends keyword. The ordering inside a single mapping file still needs to be defined as superclasses before subclasses.

<hibernate-mapping> <subclass name="DomesticCat" extends="Cat" discriminator-value="D"> <property name="name" type="string"/> </subclass> </hibernate-mapping>

Hibernate's implementation of table per subclass does not require a discriminator column. Other object/relational mappers use a different implementation of table per subclass that requires a type discriminator column in the superclass table. The approach taken by Hibernate is much more difficult to implement, but arguably more correct from a relational point of view. If you want to use a discriminator column with the table per subclass strategy, you can combine the use of <subclass> and <join>, as follows:

<class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> ... <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <join table="CREDIT_PAYMENT"> <key column="PAYMENT_ID"/> <property name="creditCardType" column="CCTYPE"/> ... </join> </subclass> <subclass name="CashPayment" discriminator-value="CASH"> <join table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> ... </join> </subclass> <subclass name="ChequePayment" discriminator-value="CHEQUE"> <join table="CHEQUE_PAYMENT" fetch="select"> <key column="PAYMENT_ID"/> ... </join> </subclass> </class>

선택적인 fetch="select" 선언은 슈퍼클래스를 질의할 때 outer join을 사용하여 ChequePayment 서브클래스 데이터를 페치시키지 않도록 Hibernate에게 알려준다.

There are two ways we can map the table per concrete class strategy. First, you can use <union-subclass>.

<class name="Payment"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="sequence"/> </id> <property name="amount" column="AMOUNT"/> ... <union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT"> <property name="creditCardType" column="CCTYPE"/> ... </union-subclass> <union-subclass name="CashPayment" table="CASH_PAYMENT"> ... </union-subclass> <union-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> ... </union-subclass> </class>

세 개의 테이블들이 슈퍼클래스들에 대해 수반된다. 각각의 테이블은 상속된 프로퍼티들을 포함하여, 그 클래스의 모든 프로퍼티들에 대한 컬럼들을 정의한다.

The limitation of this approach is that if a property is mapped on the superclass, the column name must be the same on all subclass tables. The identity generator strategy is not allowed in union subclass inheritance. The primary key seed has to be shared across all unioned subclasses of a hierarchy.

If your superclass is abstract, map it with abstract="true". If it is not abstract, an additional table (it defaults to PAYMENT in the example above), is needed to hold instances of the superclass.

대안적인 접근법은 함축적인 다형성을 사용하는 것이다:

<class name="CreditCardPayment" table="CREDIT_PAYMENT"> <id name="id" type="long" column="CREDIT_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CREDIT_AMOUNT"/> ... </class> <class name="CashPayment" table="CASH_PAYMENT"> <id name="id" type="long" column="CASH_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CASH_AMOUNT"/> ... </class> <class name="ChequePayment" table="CHEQUE_PAYMENT"> <id name="id" type="long" column="CHEQUE_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CHEQUE_AMOUNT"/> ... </class>

Notice that the Payment interface is not mentioned explicitly. Also notice that properties of Payment are mapped in each of the subclasses. If you want to avoid duplication, consider using XML entities (for example, [ <!ENTITY allproperties SYSTEM "allproperties.xml"> ] in the DOCTYPE declaration and &allproperties; in the mapping).

이 접근법의 단점은 다형성 질의들을 수행할 때 Hibernate가 생성된 SQl UNION들을 생성시키는 않는다는 점이다.

이 매핑 방도의 경우, Payment에 대한 하나의 다형성 연관은 대개 <any>를 사용하여 매핑된다.

<any name="payment" meta-type="string" id-type="long"> <meta-value value="CREDIT" class="CreditCardPayment"/> <meta-value value="CASH" class="CashPayment"/> <meta-value value="CHEQUE" class="ChequePayment"/> <column name="PAYMENT_CLASS"/> <column name="PAYMENT_ID"/> </any>

Since the subclasses are each mapped in their own <class> element, and since Payment is just an interface), each of the subclasses could easily be part of another inheritance hierarchy. You can still use polymorphic queries against the Payment interface.

<class name="CreditCardPayment" table="CREDIT_PAYMENT"> <id name="id" type="long" column="CREDIT_PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="CREDIT_CARD" type="string"/> <property name="amount" column="CREDIT_AMOUNT"/> ... <subclass name="MasterCardPayment" discriminator-value="MDC"/> <subclass name="VisaPayment" discriminator-value="VISA"/> </class> <class name="NonelectronicTransaction" table="NONELECTRONIC_TXN"> <id name="id" type="long" column="TXN_ID"> <generator class="native"/> </id> ... <joined-subclass name="CashPayment" table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> <property name="amount" column="CASH_AMOUNT"/> ... </joined-subclass> <joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> <key column="PAYMENT_ID"/> <property name="amount" column="CHEQUE_AMOUNT"/> ... </joined-subclass> </class>

Once again, Payment is not mentioned explicitly. If we execute a query against the Payment interface, for example from Payment, Hibernate automatically returns instances of CreditCardPayment (and its subclasses, since they also implement Payment), CashPayment and ChequePayment, but not instances of NonelectronicTransaction.

Hibernate is a full object/relational mapping solution that not only shields the developer from the details of the underlying database management system, but also offers state management of objects. This is, contrary to the management of SQL statements in common JDBC/SQL persistence layers, a natural object-oriented view of persistence in Java applications.

달리 말해, Hibernate 어플리케이션 개발자들은 그들의 객체들의 상태에 대해 항상 생각해야 하고, SQL 문장들의 실행에 대해서는 필수적이지 않다. 이 부분은 Hibernate에 의해 처리되고 시스템의 퍼포먼스를 튜닝할 때 어플리케이션 개발자와 유일하게 관련된다.

Hibernate 다음 객체 상태들을 정의하고 지원한다:

  • Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

  • Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

  • Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

We will now discuss the states and state transitions (and the Hibernate methods that trigger a transition) in more detail.

하나의 영속 클래스의 새로이 초기화 된 인스턴스들은 Hibernate에 의해 transient로 간주된다. 우리는 그것을 세션과 연관지어서 transient 인스턴스를 영속화 시킬 수 있다:

DomesticCat fritz = new DomesticCat(); fritz.setColor(Color.GINGER); fritz.setSex('M'); fritz.setName("Fritz"); Long generatedId = (Long) sess.save(fritz);

If Cat has a generated identifier, the identifier is generated and assigned to the cat when save() is called. If Cat has an assigned identifier, or a composite key, the identifier should be assigned to the cat instance before calling save(). You can also use persist() instead of save(), with the semantics defined in the EJB3 early draft.

  • persist() makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

  • save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context.

Alternatively, you can assign the identifier using an overloaded version of save().

DomesticCat pk = new DomesticCat(); pk.setColor(Color.TABBY); pk.setSex('F'); pk.setName("PK"); pk.setKittens( new HashSet() ); pk.addKitten(fritz); sess.save( pk, new Long(1234) );

If the object you make persistent has associated objects (e.g. the kittens collection in the previous example), these objects can be made persistent in any order you like unless you have a NOT NULL constraint upon a foreign key column. There is never a risk of violating foreign key constraints. However, you might violate a NOT NULL constraint if you save() the objects in the wrong order.

Usually you do not bother with this detail, as you will normally use Hibernate's transitive persistence feature to save the associated objects automatically. Then, even NOT NULL constraint violations do not occur - Hibernate will take care of everything. Transitive persistence is discussed later in this chapter.

The load() methods of Session provide a way of retrieving a persistent instance if you know its identifier. load() takes a class object and loads the state into a newly instantiated instance of that class in a persistent state.

Cat fritz = (Cat) sess.load(Cat.class, generatedId);
// you need to wrap primitive identifiers long id = 1234; DomesticCat pk = (DomesticCat) sess.load( DomesticCat.class, new Long(id) );

다른 방법으로 당신은 주어진 인스턴스 속으로 상태를 로드시킬 수 있다:

Cat cat = new DomesticCat(); // load pk's state into cat sess.load( cat, new Long(pkId) ); Set kittens = cat.getKittens();

Be aware that load() will throw an unrecoverable exception if there is no matching database row. If the class is mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This is useful if you wish to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batch-size is defined for the class mapping.

If you are not certain that a matching row exists, you should use the get() method which hits the database immediately and returns null if there is no matching row.

Cat cat = (Cat) sess.get(Cat.class, id); if (cat==null) { cat = new Cat(); sess.save(cat, id); } return cat;

You can even load an object using an SQL SELECT ... FOR UPDATE, using a LockMode. See the API documentation for more information.

Cat cat = (Cat) sess.get(Cat.class, id, LockMode.UPGRADE);

Any associated instances or contained collections will not be selected FOR UPDATE, unless you decide to specify lock or all as a cascade style for the association.

refresh() 메소드를 사용하여, 아무때나 하나의 객체와 모든 그것의 콜렉션들을 다시 로드시키는 것이 가능하다. 데이터베이스 트리거들이 그 객체의 프로퍼티들 중 어떤 것을 초기화 시키는데 사용될 때 이것이 유용하다.

sess.save(cat); sess.flush(); //force the SQL INSERT sess.refresh(cat); //re-read the state (after the trigger executes)

How much does Hibernate load from the database and how many SQL SELECTs will it use? This depends on the fetching strategy. This is explained in 19.1절. “페칭 방도들”.

If you do not know the identifiers of the objects you are looking for, you need a query. Hibernate supports an easy-to-use but powerful object oriented query language (HQL). For programmatic query creation, Hibernate supports a sophisticated Criteria and Example query feature (QBC and QBE). You can also express your query in the native SQL of your database, with optional support from Hibernate for result set conversion into objects.

HQL 질의와 native SQL 질의는 org.hibernate.Query의 인스턴스로 표현된다. 이 인터페이스는 파라미터 바인딩, 결과셋 핸들링을 위한, 그리고 실제 질의의 실행을 위한 메소드들을 제공한다. 당신은 항상 현재 Session을 사용하여 하나의 Query를 얻는다:

List cats = session.createQuery( "from Cat as cat where cat.birthdate < ?") .setDate(0, date) .list(); List mothers = session.createQuery( "select mother from Cat as cat join cat.mother as mother where cat.name = ?") .setString(0, name) .list(); List kittens = session.createQuery( "from Cat as cat where cat.mother = ?") .setEntity(0, pk) .list(); Cat mother = (Cat) session.createQuery( "select cat.mother from Cat as cat where cat = ?") .setEntity(0, izi) .uniqueResult();]] Query mothersWithKittens = (Cat) session.createQuery( "select mother from Cat as mother left join fetch mother.kittens"); Set uniqueMothers = new HashSet(mothersWithKittens.list());

A query is usually executed by invoking list(). The result of the query will be loaded completely into a collection in memory. Entity instances retrieved by a query are in a persistent state. The uniqueResult() method offers a shortcut if you know your query will only return a single object. Queries that make use of eager fetching of collections usually return duplicates of the root objects, but with their collections initialized. You can filter these duplicates through a Set.

Occasionally, you might be able to achieve better performance by executing the query using the iterate() method. This will usually be the case if you expect that the actual entity instances returned by the query will already be in the session or second-level cache. If they are not already cached, iterate() will be slower than list() and might require many database hits for a simple query, usually 1 for the initial select which only returns identifiers, and n additional selects to initialize the actual instances.

// fetch ids Iterator iter = sess.createQuery("from eg.Qux q order by q.likeliness").iterate(); while ( iter.hasNext() ) { Qux qux = (Qux) iter.next(); // fetch the object // something we couldnt express in the query if ( qux.calculateComplicatedAlgorithm() ) { // delete the current instance iter.remove(); // dont need to process the rest break; } }

Methods on Query are provided for binding values to named parameters or JDBC-style ? parameters. Contrary to JDBC, Hibernate numbers parameters from zero. Named parameters are identifiers of the form :name in the query string. The advantages of named parameters are as follows:

  • 명명된 파라미터들은 그것들이 질의 문자열 내에 발생하는 순서에 관계없다

  • they can occur multiple times in the same query

  • 그것은 자기-설명적이다

//named parameter (preferred) Query q = sess.createQuery("from DomesticCat cat where cat.name = :name"); q.setString("name", "Fritz"); Iterator cats = q.iterate();
//positional parameter Query q = sess.createQuery("from DomesticCat cat where cat.name = ?"); q.setString(0, "Izi"); Iterator cats = q.iterate();
//named parameter list List names = new ArrayList(); names.add("Izi"); names.add("Fritz"); Query q = sess.createQuery("from DomesticCat cat where cat.name in (:namesList)"); q.setParameterList("namesList", names); List cats = q.list();

If you need to specify bounds upon your result set, that is, the maximum number of rows you want to retrieve and/or the first row you want to retrieve, you can use methods of the Query interface:

Query q = sess.createQuery("from DomesticCat cat"); q.setFirstResult(20); q.setMaxResults(10); List cats = q.list();

Hibernate는 이 limit 질의를 당신의 DBMS의 native SQL로 번역하는 방법을 알고 있다.

You can also define named queries in the mapping document. Remember to use a CDATA section if your query contains characters that could be interpreted as markup.

<query name="ByNameAndMaximumWeight"><![CDATA[ from eg.DomesticCat as cat where cat.name = ? and cat.weight > ? ] ]></query>

파라미터 바인딩과 실행은 프로그램 상으로 행해진다:

Query q = sess.getNamedQuery("ByNameAndMaximumWeight"); q.setString(0, name); q.setInt(1, minWeight); List cats = q.list();

The actual program code is independent of the query language that is used. You can also define native SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.

Also note that a query declaration inside a <hibernate-mapping> element requires a global unique name for the query, while a query declaration inside a <class> element is made unique automatically by prepending the fully qualified name of the class. For example eg.Cat.ByNameAndMaximumWeight.

A collection filter is a special type of query that can be applied to a persistent collection or array. The query string can refer to this, meaning the current collection element.

Collection blackKittens = session.createFilter( pk.getKittens(), "where this.color = ?") .setParameter( Color.BLACK, Hibernate.custom(ColorUserType.class) ) .list() );

The returned collection is considered a bag that is a copy of the given collection. The original collection is not modified. This is contrary to the implication of the name "filter", but consistent with expected behavior.

Observe that filters do not require a from clause, although they can have one if required. Filters are not limited to returning the collection elements themselves.

Collection blackKittenMates = session.createFilter( pk.getKittens(), "select this.mate where this.color = eg.Color.BLACK.intValue") .list();

Even an empty filter query is useful, e.g. to load a subset of elements in a large collection:

Collection tenKittens = session.createFilter( mother.getKittens(), "") .setFirstResult(0).setMaxResults(10) .list();

HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases:

Criteria crit = session.createCriteria(Cat.class); crit.add( Restrictions.eq( "color", eg.Color.BLACK ) ); crit.setMaxResults(10); List cats = crit.list();

Criteria와 연관된 Example API 는 15장. Criteria 질의들에서 상세하게 논의된다.

Transactional persistent instances (i.e. objects loaded, saved, created or queried by the Session) can be manipulated by the application, and any changes to persistent state will be persisted when the Session is flushed. This is discussed later in this chapter. There is no need to call a particular method (like update(), which has a different purpose) to make your modifications persistent. The most straightforward way to update the state of an object is to load() it and then manipulate it directly while the Session is open:

DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) ); cat.setName("PK"); sess.flush(); // changes to cat are automatically detected and persisted

Sometimes this programming model is inefficient, as it requires in the same session both an SQL SELECT to load an object and an SQL UPDATE to persist its updated state. Hibernate offers an alternate approach by using detached instances.

많은 어플리케이션들은 하나의 트랜잭션 내에서 하나의 객체를 검색하고, 처리를 위한 UI 계층으로 그것을 전송하고, 그런 다음 새로운 트랜잭션 내에서 변경들을 저장할 필요가 있다. 고도의-동시성 환경에서 이런 종류의 접근법을 사용하는 어플리케이션들은 대개 작업의 "긴" 단위를 확실히 격리시키기 위해 버전화 된 데이터를 사용한다.

Hibernate는 Session.update() 메소드 또는 Session.merge() 메소드를 사용하여 detached 인스턴스들의 재첨부를 제공함으로써 이 모형을 지원한다:

// in the first session Cat cat = (Cat) firstSession.load(Cat.class, catId); Cat potentialMate = new Cat(); firstSession.save(potentialMate); // in a higher layer of the application cat.setMate(potentialMate); // later, in a new session secondSession.update(cat); // update cat secondSession.update(mate); // update mate

만일 catId 식별자를 가진 Cat이 secondSession에 의해 이미 로드되었을 경우에 어플리케이션이 그것을 다시 재첨부하려고 시도할 때, 예외상황이 던져졌을 것이다.

Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session. In other words, update() is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed.

The application should individually update() detached instances that are reachable from the given detached instance only if it wants their state to be updated. This can be automated using transitive persistence. See 10.11절. “Transitive persistence(전이 영속)” for more information.

The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified.

//just reassociate: sess.lock(fritz, LockMode.NONE); //do a version check, then reassociate: sess.lock(izi, LockMode.READ); //do a version check, using SELECT ... FOR UPDATE, then reassociate: sess.lock(pk, LockMode.UPGRADE);

Note that lock() can be used with various LockModes. See the API documentation and the chapter on transaction handling for more information. Reattachment is not the only usecase for lock().

긴 작업 단위에 대한 다른 모형들은 11.3절. “Optimistic 동시성 제어”에서 논의된다.

Hibernate 사용자들은 새로운 식별자를 생성시켜서 transient 인스턴스를 저장하거나 그것의 현재 식별자와 연관된 detached 인스턴스들을 업데이트/재첨부 시키는 일반적인 용도의 메소드를 요청했다. saveOrUpdate() 메소드는 이 기능을 구현한다.

// in the first session Cat cat = (Cat) firstSession.load(Cat.class, catID); // in a higher tier of the application Cat mate = new Cat(); cat.setMate(mate); // later, in a new session secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id) secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)

saveOrUpdate()의 사용 예제와 의미는 초심자들에게는 혼동스러워 보인다. 먼저, 하나의 세션에서 온 인스턴스를 또 다른 새로운 세션 내에서 사용하려고 시도하지 않는 한, 당신은 update()saveOrUpdate(), 또는 merge()를 사용할 필요는 없을 것이다. 몇몇 전체 어플리케이션들은 이들 메소드들 중 어느 것도 결코 사용하지 않을 것이다.

대개 update() 또는 saveOrUpdate()는 다음 시나리오에서 사용된다:

  • 어플리케이션이 첫 번째 세션 내에 객체를 로드시킨다

  • 객체가 UI 티어로 전달된다

  • 몇몇 변경들이 그 객체에 행해진다

  • 객체가 비지니스 로직 티어로 전달된다

  • 어플리케이션은 두 번째 세션에서 update()를 호출함으로써 이들 변경들을 영속화 시킨다

saveOrUpdate()는 다음을 행한다:

  • 만일 객체가 이 세션 내에서 이미 영속화 되어 있을 경우, 아무것도 행하지 않는다

  • 만일 그 세션과 연관된 또 다른 객체가 동일한 식별자를 가질 경우, 예외상황을 던진다

  • 만일 그 객체가 식별자 프로퍼티를 갖지 않을 경우, 그것을 save() 시킨다

  • 만일 객체의 식별자가 새로이 초기화 된 객체에 할당된 값을 가질 경우, 그것을 save() 시킨다

  • if the object is versioned by a <version> or <timestamp>, and the version property value is the same value assigned to a newly instantiated object, save() it

  • 그 밖의 경우 그 객체를 update() 시킨다

그리고 merge()는 매우 다르다:

  • 만일 세션과 현재 연관된 동일한 식별자를 가진 영속 인스턴스가 존재할 경우, 주어진 객체의 상태를 영속 인스턴스 상으로 복사한다

  • 만일 세션과 현재 연관된 영속 인스턴스가 존재하지 않을 경우, 데이터베이스로부터 그것을 로드시키려고 시도하거나 새로운 영속 인스턴스를 생성시키려고 시도한다

  • 영속 인스턴스가 반환된다

  • 주어진 인스턴스는 세션과 연관되지 않고, 그것은 detached 상태에 머무른다

Session.delete() will remove an object's state from the database. Your application, however, can still hold a reference to a deleted object. It is best to think of delete() as making a persistent instance, transient.

sess.delete(cat);

You can delete objects in any order, without risk of foreign key constraint violations. It is still possible to violate a NOT NULL constraint on a foreign key column by deleting objects in the wrong order, e.g. if you delete the parent, but forget to delete the children.

It is sometimes useful to be able to take a graph of persistent instances and make them persistent in a different datastore, without regenerating identifier values.

//retrieve a cat from one database Session session1 = factory1.openSession(); Transaction tx1 = session1.beginTransaction(); Cat cat = session1.get(Cat.class, catId); tx1.commit(); session1.close(); //reconcile with a second database Session session2 = factory2.openSession(); Transaction tx2 = session2.beginTransaction(); session2.replicate(cat, ReplicationMode.LATEST_VERSION); tx2.commit(); session2.close();

The ReplicationMode determines how replicate() will deal with conflicts with existing rows in the database:

  • ReplicationMode.IGNORE: ignores the object when there is an existing database row with the same identifier

  • ReplicationMode.OVERWRITE: overwrites any existing database row with the same identifier

  • ReplicationMode.EXCEPTION: throws an exception if there is an existing database row with the same identifier

  • ReplicationMode.LATEST_VERSION: overwrites the row if its version number is earlier than the version number of the object, or ignore the object otherwise

이 특징의 쓰임새들은 다른 데이터베이스 인스턴스들 속으로 입력된 데이터 일치시키기, 제품 업그레이드 동안에 시스템 구성 정보 업데이트 하기, non-ACID 트랜잭션들 동안에 행해진 변경들을 롤백시키기 등을 포함한다.

Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush, occurs by default at the following points:

  • 몇몇 질의들이 실행되기 전에

  • org.hibernate.Transaction.commit() 시점에서

  • Session.flush() 시점에서

The SQL statements are issued in the following order:

  1. all entity insertions in the same order the corresponding objects were saved using Session.save()

  2. 모든 엔티티 업데이트들

  3. 모든 콜렉션 삭제들

  4. 모든 콜렉션 요소 삭제들, 업데이트들 그리고 삽입들

  5. 모든 콜렉션 삽입들

  6. all entity deletions in the same order the corresponding objects were deleted using Session.delete()

An exception is that objects using native ID generation are inserted when they are saved.

Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data.

It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time when the Hibernate Transaction API is used, flush automatically using the explained routine, or never flush unless flush() is called explicitly. The last mode is useful for long running units of work, where a Session is kept open and disconnected for a long time (see 11.3.2절. “확장된 세션과 자동적인 버전화”).

sess = sf.openSession(); Transaction tx = sess.beginTransaction(); sess.setFlushMode(FlushMode.COMMIT); // allow queries to return stale state Cat izi = (Cat) sess.load(Cat.class, id); izi.setName(iznizi); // might return stale data sess.find("from Cat as cat left outer join cat.kittens kitten"); // change to izi is not flushed! ... tx.commit(); // flush occurs sess.close();

flush 동안에, 하나의 예외상황이 발생할 수도 있다(예를 들면. 만일 DML 오퍼레이션이 컨스트레인트를 위반할 경우). 예외상황들을 처리하는 것은 Hibernatem의 트랜잭션 특징에 관한 어떤 이해를 수반하며, 우리는 11장. Transactions and Concurrency에서 그것을 논의한다.

특히 당신이 연관된 객체들의 그래프를 다룰 경우에, 특히 개별 객체들을 저장하고, 삭제하거나, 재첨부시키는 것이 꽤 번거롭다. 공통된 경우는 하나의 부모/자식 관계이다. 다음 예제를 검토하자:

If the children in a parent/child relationship would be value typed (e.g. a collection of addresses or strings), their life cycle would depend on the parent and no further action would be required for convenient "cascading" of state changes. When the parent is saved, the value-typed child objects are saved and when the parent is deleted, the children will be deleted, etc. This works for operations such as the removal of a child from the collection. Since value-typed objects cannot have shared references, Hibernate will detect this and delete the child from the database.

Now consider the same scenario with parent and child objects being entities, not value-types (e.g. categories and items, or parent and child cats). Entities have their own life cycle and support shared references. Removing an entity from the collection does not mean it can be deleted), and there is by default no cascading of state from one entity to any other associated entities. Hibernate does not implement persistence by reachability by default.

persist(), merge(), saveOrUpdate(), delete(), lock(), refresh(), evict(), replicate()를 포함하는- Hibernate 세션에 대한 각각의 기본 오퍼레이션에 대해서 하나의 대응하는 케스케이딩 스타일이 존재한다. 케스케이드 스타일들 각각은 create, merge, save-update, delete, lock, refresh, evict, replicate로 명명된다. 만일 당신이 하나의 오퍼레이션이 하나의 연관에 따라 케스케이딩되는 것을 원할 경우, 당신은 매핑 문서 내에 그것을 지시해야 한다. 예를 들면:

<one-to-one name="person" cascade="persist"/>

케스케이딩 스타일들이 결합될 수도 있다:

<one-to-one name="person" cascade="persist,delete,lock"/>

You can even use cascade="all" to specify that all operations should be cascaded along the association. The default cascade="none" specifies that no operations are to be cascaded.

특정한 케스케이드 스타일인, delete-orphan은 오직 one-to-many 연관들에만 적용되고, delete() 오퍼레이션이 그 연관으로부터 제거되는 임의의 자식 객체에 적용되어야 함을 나타낸다.

권장사항들 :

  • It does not usually make sense to enable cascade on a <many-to-one> or <many-to-many> association. Cascade is often useful for <one-to-one> and <one-to-many> associations.

  • 만일 자식 객체의 수명이 그 부모 객체의 수명에 묶여져 있을 경우, cascade="all,delete-orphan"을 지정함으로써 그것을 생명 주기 객체로 만들어라.

  • 그 밖의 경우, 당신은 케스케이드를 전혀 필요로 하지 않을 수 있다. 그러나 만일 당신이 동일한 트랜잭션 내에서 부모와 자식에 대해 자주 함께 작업하게 될 것이라 생각되고, 당신 스스로 타이핑 하는 것을 절약하고자 원할 경우, cascade="persist,merge,save-update"를 사용하는 것을 고려하라.

cascade="all"을 가진 (단일 값 연관이든 하나의 콜렉션이든) 하나의 연관을 매핑시키는 것은 그 연관을 부모의 저장/업데이트/삭제가 자식 또는 자식들의 저장/업데이트/삭제로 귀결되는 부모/자식 스타일의 관계로 마크한다.

Furthermore, a mere reference to a child from a persistent parent will result in save/update of the child. This metaphor is incomplete, however. A child which becomes unreferenced by its parent is not automatically deleted, except in the case of a <one-to-many> association mapped with cascade="delete-orphan". The precise semantics of cascading operations for a parent/child relationship are as follows:

  • 만일 부모가 persist()에 전달될 경우, 모든 자식들이 persist()에 전달된다

  • 만일 부모가 merge()에 전달될 경우, 모든 자식들이 merge()에 전달된다

  • 만일 부모가 save()update() 또는 saveOrUpdate()에 전달될 경우, 모든 자식들이 saveOrUpdate()에 전달된다

  • 만일 transient 또는 detached 자식이 영속 부모에 의해 참조될 경우, 그것은 saveOrUpdate()에 전달된다

  • 만일 부모가 삭제될 경우, 모든 자식들이 delete()에 전달된다

  • 만일 자식이 영속 부모에 의해 참조 해제 될 경우, cascade="delete-orphan"이 아닌 한, 특별한 어떤 것도 발생하지 않는다 - 어플리케이션은 필요한 경우에 자식을 명시적으로 삭제해야 한다 -, cascade="delete-orphan"인 경우에 "orphaned(고아)"인 경우 자식이 삭제된다.

Finally, note that cascading of operations can be applied to an object graph at call time or at flush time. All operations, if enabled, are cascaded to associated entities reachable when the operation is executed. However, save-update and delete-orphan are transitive for all associated entities reachable during flush of the Session.

Hibernate requires a rich meta-level model of all entity and value types. This model can be useful to the application itself. For example, the application might use Hibernate's metadata to implement a "smart" deep-copy algorithm that understands which objects should be copied (eg. mutable value types) and which objects that should not (e.g. immutable value types and, possibly, associated entities).

Hibernate exposes metadata via the ClassMetadata and CollectionMetadata interfaces and the Type hierarchy. Instances of the metadata interfaces can be obtained from the SessionFactory.

Cat fritz = ......; ClassMetadata catMeta = sessionfactory.getClassMetadata(Cat.class); Object[] propertyValues = catMeta.getPropertyValues(fritz); String[] propertyNames = catMeta.getPropertyNames(); Type[] propertyTypes = catMeta.getPropertyTypes(); // get a Map of all properties which are not collections or associations Map namedValues = new HashMap(); for ( int i=0; i<propertyNames.length; i++ ) { if ( !propertyTypes[i].isEntityType() && !propertyTypes[i].isCollectionType() ) { namedValues.put( propertyNames[i], propertyValues[i] ); } }

The most important point about Hibernate and concurrency control is that it is easy to understand. Hibernate directly uses JDBC connections and JTA resources without adding any additional locking behavior. It is recommended that you spend some time with the JDBC, ANSI, and transaction isolation specification of your database management system.

Hibernate does not lock objects in memory. Your application can expect the behavior as defined by the isolation level of your database transactions. Through Session, which is also a transaction-scoped cache, Hibernate provides repeatable reads for lookup by identifier and entity queries and not reporting queries that return scalar values.

In addition to versioning for automatic optimistic concurrency control, Hibernate also offers, using the SELECT FOR UPDATE syntax, a (minor) API for pessimistic locking of rows. Optimistic concurrency control and this API are discussed later in this chapter.

The discussion of concurrency control in Hibernate begins with the granularity of ConfigurationSessionFactory, and Session, as well as database transactions and long conversations.

SessionFactory is an expensive-to-create, threadsafe object, intended to be shared by all application threads. It is created once, usually on application startup, from a Configuration instance.

Session is an inexpensive, non-threadsafe object that should be used once and then discarded for: a single request, a conversation or a single unit of work. A Session will not obtain a JDBC Connection, or a Datasource, unless it is needed. It will not consume any resources until used.

In order to reduce lock contention in the database, a database transaction has to be as short as possible. Long database transactions will prevent your application from scaling to a highly concurrent load. It is not recommended that you hold a database transaction open during user think time until the unit of work is complete.

What is the scope of a unit of work? Can a single Hibernate Session span several database transactions, or is this a one-to-one relationship of scopes? When should you open and close a Session and how do you demarcate the database transaction boundaries? These questions are addressed in the following sections.

First, let's define a unit of work. A unit of work is a design pattern described by Martin Fowler as “ [maintaining] a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. ”[PoEAA] In other words, its a series of operations we wish to carry out against the database together. Basically, it is a transaction, though fulfilling a unit of work will often span multiple physical database transactions (see 11.1.2절. “장기간의 대화”). So really we are talking about a more abstract notion of a transaction. The term "business transaction" is also sometimes used in lieu of unit of work.

Do not use the session-per-operation antipattern: do not open and close a Session for every simple database call in a single thread. The same is true for database transactions. Database calls in an application are made using a planned sequence; they are grouped into atomic units of work. This also means that auto-commit after every single SQL statement is useless in an application as this mode is intended for ad-hoc SQL console work. Hibernate disables, or expects the application server to disable, auto-commit mode immediately. Database transactions are never optional. All communication with a database has to occur inside a transaction. Auto-commit behavior for reading data should be avoided, as many small transactions are unlikely to perform better than one clearly defined unit of work. The latter is also more maintainable and extensible.

The most common pattern in a multi-user client/server application is session-per-request. In this model, a request from the client is sent to the server, where the Hibernate persistence layer runs. A new Hibernate Session is opened, and all database operations are executed in this unit of work. On completion of the work, and once the response for the client has been prepared, the session is flushed and closed. Use a single database transaction to serve the clients request, starting and committing it when you open and close the Session. The relationship between the two is one-to-one and this model is a perfect fit for many applications.

The challenge lies in the implementation. Hibernate provides built-in management of the "current session" to simplify this pattern. Start a transaction when a server request has to be processed, and end the transaction before the response is sent to the client. Common solutions are ServletFilter, AOP interceptor with a pointcut on the service methods, or a proxy/interception container. An EJB container is a standardized way to implement cross-cutting aspects such as transaction demarcation on EJB session beans, declaratively with CMT. If you use programmatic transaction demarcation, for ease of use and code portability use the Hibernate Transaction API shown later in this chapter.

Your application code can access a "current session" to process the request by calling sessionFactory.getCurrentSession(). You will always get a Session scoped to the current database transaction. This has to be configured for either resource-local or JTA environments, see 2.5절. “Contextual sessions”.

You can extend the scope of a Session and database transaction until the "view has been rendered". This is especially useful in servlet applications that utilize a separate rendering phase after the request has been processed. Extending the database transaction until view rendering, is achieved by implementing your own interceptor. However, this will be difficult if you rely on EJBs with container-managed transactions. A transaction will be completed when an EJB method returns, before rendering of any view can start. See the Hibernate website and forum for tips and examples relating to this Open Session in View pattern.

The session-per-request pattern is not the only way of designing units of work. Many business processes require a whole series of interactions with the user that are interleaved with database accesses. In web and enterprise applications, it is not acceptable for a database transaction to span a user interaction. Consider the following example:

  • The first screen of a dialog opens. The data seen by the user has been loaded in a particular Session and database transaction. The user is free to modify the objects.

  • The user clicks "Save" after 5 minutes and expects their modifications to be made persistent. The user also expects that they were the only person editing this information and that no conflicting modification has occurred.

From the point of view of the user, we call this unit of work a long-running conversation or application transaction. There are many ways to implement this in your application.

A first naive implementation might keep the Session and database transaction open during user think time, with locks held in the database to prevent concurrent modification and to guarantee isolation and atomicity. This is an anti-pattern, since lock contention would not allow the application to scale with the number of concurrent users.

You have to use several database transactions to implement the conversation. In this case, maintaining isolation of business processes becomes the partial responsibility of the application tier. A single conversation usually spans several database transactions. It will be atomic if only one of these database transactions (the last one) stores the updated data. All others simply read data (for example, in a wizard-style dialog spanning several request/response cycles). This is easier to implement than it might sound, especially if you utilize some of Hibernate's features:

  • Automatic Versioning: Hibernate can perform automatic optimistic concurrency control for you. It can automatically detect if a concurrent modification occurred during user think time. Check for this at the end of the conversation.

  • Detached Objects: if you decide to use the session-per-request pattern, all loaded instances will be in the detached state during user think time. Hibernate allows you to reattach the objects and persist the modifications. The pattern is called session-per-request-with-detached-objects. Automatic versioning is used to isolate concurrent modifications.

  • Extended (or Long) Session: the Hibernate Session can be disconnected from the underlying JDBC connection after the database transaction has been committed and reconnected when a new client request occurs. This pattern is known as session-per-conversation and makes even reattachment unnecessary. Automatic versioning is used to isolate concurrent modifications and the Session will not be allowed to be flushed automatically, but explicitly.

Both session-per-request-with-detached-objects and session-per-conversation have advantages and disadvantages. These disadvantages are discussed later in this chapter in the context of optimistic concurrency control.

An application can concurrently access the same persistent state in two different Sessions. However, an instance of a persistent class is never shared between two Session instances. It is for this reason that there are two different notions of identity:

For objects attached to a particular Session (i.e., in the scope of a Session), the two notions are equivalent and JVM identity for database identity is guaranteed by Hibernate. While the application might concurrently access the "same" (persistent identity) business object in two different sessions, the two instances will actually be "different" (JVM identity). Conflicts are resolved using an optimistic approach and automatic versioning at flush/commit time.

This approach leaves Hibernate and the database to worry about concurrency. It also provides the best scalability, since guaranteeing identity in single-threaded units of work means that it does not need expensive locking or other means of synchronization. The application does not need to synchronize on any business object, as long as it maintains a single thread per Session. Within a Session the application can safely use == to compare objects.

However, an application that uses == outside of a Session might produce unexpected results. This might occur even in some unexpected places. For example, if you put two detached instances into the same Set, both might have the same database identity (i.e., they represent the same row). JVM identity, however, is by definition not guaranteed for instances in a detached state. The developer has to override the equals() and hashCode() methods in persistent classes and implement their own notion of object equality. There is one caveat: never use the database identifier to implement equality. Use a business key that is a combination of unique, usually immutable, attributes. The database identifier will change if a transient object is made persistent. If the transient instance (usually together with detached instances) is held in a Set, changing the hashcode breaks the contract of the Set. Attributes for business keys do not have to be as stable as database primary keys; you only have to guarantee stability as long as the objects are in the same Set. See the Hibernate website for a more thorough discussion of this issue. Please note that this is not a Hibernate issue, but simply how Java object identity and equality has to be implemented.

Do not use the anti-patterns session-per-user-session or session-per-application (there are, however, rare exceptions to this rule). Some of the following issues might also arise within the recommended patterns, so ensure that you understand the implications before making a design decision:

Database, or system, transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations. Depending on your isolation level and database capabilities this might not be required, but there is no downside if you always demarcate transactions explicitly. Certainly, a single database transaction is going to perform better than many small transactions, even for reading data.

A Hibernate application can run in non-managed (i.e., standalone, simple Web- or Swing applications) and managed J2EE environments. In a non-managed environment, Hibernate is usually responsible for its own database connection pool. The application developer has to manually set transaction boundaries (begin, commit, or rollback database transactions) themselves. A managed environment usually provides container-managed transactions (CMT), with the transaction assembly defined declaratively (in deployment descriptors of EJB session beans, for example). Programmatic transaction demarcation is then no longer necessary.

However, it is often desirable to keep your persistence layer portable between non-managed resource-local environments, and systems that can rely on JTA but use BMT instead of CMT. In both cases use programmatic transaction demarcation. Hibernate offers a wrapper API called Transaction that translates into the native transaction system of your deployment environment. This API is actually optional, but we strongly encourage its use unless you are in a CMT session bean.

Ending a Session usually involves four distinct phases:

  • 세션을 flush 시킨다

  • 트랜잭션을 커밋 시킨다

  • 세션을 닫는다

  • 예외상황들을 처리한다

We discussed Flushing the session earlier, so we will now have a closer look at transaction demarcation and exception handling in both managed and non-managed environments.

If a Hibernate persistence layer runs in a non-managed environment, database connections are usually handled by simple (i.e., non-DataSource) connection pools from which Hibernate obtains connections as needed. The session/transaction handling idiom looks like this:

// Non-managed environment idiom Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); }

You do not have to flush() the Session explicitly: the call to commit() automatically triggers the synchronization depending on the FlushMode for the session. A call to close() marks the end of a session. The main implication of close() is that the JDBC connection will be relinquished by the session. This Java code is portable and runs in both non-managed and JTA environments.

As outlined earlier, a much more flexible solution is Hibernate's built-in "current session" context management:

// Non-managed environment idiom with getCurrentSession() try { factory.getCurrentSession().beginTransaction(); // do some work ... factory.getCurrentSession().getTransaction().commit(); } catch (RuntimeException e) { factory.getCurrentSession().getTransaction().rollback(); throw e; // or display error message }

You will not see these code snippets in a regular application; fatal (system) exceptions should always be caught at the "top". In other words, the code that executes Hibernate calls in the persistence layer, and the code that handles RuntimeException (and usually can only clean up and exit), are in different layers. The current context management by Hibernate can significantly simplify this design by accessing a SessionFactory. Exception handling is discussed later in this chapter.

You should select org.hibernate.transaction.JDBCTransactionFactory, which is the default, and for the second example select "thread" as your hibernate.current_session_context_class.

If your persistence layer runs in an application server (for example, behind EJB session beans), every datasource connection obtained by Hibernate will automatically be part of the global JTA transaction. You can also install a standalone JTA implementation and use it without EJB. Hibernate offers two strategies for JTA integration.

If you use bean-managed transactions (BMT), Hibernate will tell the application server to start and end a BMT transaction if you use the Transaction API. The transaction management code is identical to the non-managed environment.

// BMT idiom Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); }

If you want to use a transaction-bound Session, that is, the getCurrentSession() functionality for easy context propagation, use the JTA UserTransaction API directly:

// BMT idiom with getCurrentSession() try { UserTransaction tx = (UserTransaction)new InitialContext() .lookup("java:comp/UserTransaction"); tx.begin(); // Do some work on Session bound to transaction factory.getCurrentSession().load(...); factory.getCurrentSession().persist(...); tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; // or display error message }

With CMT, transaction demarcation is completed in session bean deployment descriptors, not programmatically. The code is reduced to:

// CMT idiom Session sess = factory.getCurrentSession(); // do some work ...

In a CMT/EJB, even rollback happens automatically. An unhandled RuntimeException thrown by a session bean method tells the container to set the global transaction to rollback. You do not need to use the Hibernate Transaction API at all with BMT or CMT, and you get automatic propagation of the "current" Session bound to the transaction.

When configuring Hibernate's transaction factory, choose org.hibernate.transaction.JTATransactionFactory if you use JTA directly (BMT), and org.hibernate.transaction.CMTTransactionFactory in a CMT session bean. Remember to also set hibernate.transaction.manager_lookup_class. Ensure that your hibernate.current_session_context_class is either unset (backwards compatibility), or is set to "jta".

The getCurrentSession() operation has one downside in a JTA environment. There is one caveat to the use of after_statement connection release mode, which is then used by default. Due to a limitation of the JTA spec, it is not possible for Hibernate to automatically clean up any unclosed ScrollableResults or Iterator instances returned by scroll() or iterate(). You must release the underlying database cursor by calling ScrollableResults.close() or Hibernate.close(Iterator) explicitly from a finally block. Most applications can easily avoid using scroll() or iterate() from the JTA or CMT code.)

If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable. Ensure that the Session will be closed by calling close() in a finally block.

The HibernateException, which wraps most of the errors that can occur in a Hibernate persistence layer, is an unchecked exception. It was not in older versions of Hibernate. In our opinion, we should not force the application developer to catch an unrecoverable exception at a low layer. In most systems, unchecked and fatal exceptions are handled in one of the first frames of the method call stack (i.e., in higher layers) and either an error message is presented to the application user or some other appropriate action is taken. Note that Hibernate might also throw other unchecked exceptions that are not a HibernateException. These are not recoverable and appropriate action should be taken.

Hibernate wraps SQLExceptions thrown while interacting with the database in a JDBCException. In fact, Hibernate will attempt to convert the exception into a more meaningful subclass of JDBCException. The underlying SQLException is always available via JDBCException.getCause(). Hibernate converts the SQLException into an appropriate JDBCException subclass using the SQLExceptionConverter attached to the SessionFactory. By default, the SQLExceptionConverter is defined by the configured dialect. However, it is also possible to plug in a custom implementation. See the javadocs for the SQLExceptionConverterFactory class for details. The standard JDBCException subtypes are:

  • JDBCConnectionException: indicates an error with the underlying JDBC communication.

  • SQLGrammarException: indicates a grammar or syntax problem with the issued SQL.

  • ConstraintViolationException: indicates some form of integrity constraint violation.

  • LockAcquisitionException: indicates an error acquiring a lock level necessary to perform the requested operation.

  • GenericJDBCException: a generic exception which did not fall into any of the other categories.

An important feature provided by a managed environment like EJB, that is never provided for non-managed code, is transaction timeout. Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. In a managed environment, Hibernate can delegate transaction timeout to JTA. This functionality is abstracted by the Hibernate Transaction object.

Session sess = factory.openSession(); try { //set transaction timeout to 3 seconds sess.getTransaction().setTimeout(3); sess.getTransaction().begin(); // do some work ... sess.getTransaction().commit() } catch (RuntimeException e) { sess.getTransaction().rollback(); throw e; // or display error message } finally { sess.close(); }

setTimeout() cannot be called in a CMT bean, where transaction timeouts must be defined declaratively.

The only approach that is consistent with high concurrency and high scalability, is optimistic concurrency control with versioning. Version checking uses version numbers, or timestamps, to detect conflicting updates and to prevent lost updates. Hibernate provides three possible approaches to writing application code that uses optimistic concurrency. The use cases we discuss are in the context of long conversations, but version checking also has the benefit of preventing lost updates in single database transactions.

In an implementation without much help from Hibernate, each interaction with the database occurs in a new Session and the developer is responsible for reloading all persistent instances from the database before manipulating them. The application is forced to carry out its own version checking to ensure conversation transaction isolation. This approach is the least efficient in terms of database access. It is the approach most similar to entity EJBs.

// foo is an instance loaded by a previous Session session = factory.openSession(); Transaction t = session.beginTransaction(); int oldVersion = foo.getVersion(); session.load( foo, foo.getKey() ); // load the current state if ( oldVersion != foo.getVersion() ) throw new StaleObjectStateException(); foo.setProperty("bar"); t.commit(); session.close();

version 프로퍼티는 <version>을 사용하여 매핑되고, Hibernate는 만일 엔티티가 dirty일 경우 flush 동안에 그것을 자동적으로 증가시킬 것이다.

If you are operating in a low-data-concurrency environment, and do not require version checking, you can use this approach and skip the version check. In this case, last commit wins is the default strategy for long conversations. Be aware that this might confuse the users of the application, as they might experience lost updates without error messages or a chance to merge conflicting changes.

Manual version checking is only feasible in trivial circumstances and not practical for most applications. Often not only single instances, but complete graphs of modified objects, have to be checked. Hibernate offers automatic version checking with either an extended Session or detached instances as the design paradigm.

A single Session instance and its persistent instances that are used for the whole conversation are known as session-per-conversation. Hibernate checks instance versions at flush time, throwing an exception if concurrent modification is detected. It is up to the developer to catch and handle this exception. Common options are the opportunity for the user to merge changes or to restart the business conversation with non-stale data.

The Session is disconnected from any underlying JDBC connection when waiting for user interaction. This approach is the most efficient in terms of database access. The application does not version check or reattach detached instances, nor does it have to reload instances in every database transaction.

// foo is an instance loaded earlier by the old session Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction foo.setProperty("bar"); session.flush(); // Only for last transaction in conversation t.commit(); // Also return JDBC connection session.close(); // Only for last transaction in conversation

The foo object knows which Session it was loaded in. Beginning a new database transaction on an old session obtains a new connection and resumes the session. Committing a database transaction disconnects a session from the JDBC connection and returns the connection to the pool. After reconnection, to force a version check on data you are not updating, you can call Session.lock() with LockMode.READ on any objects that might have been updated by another transaction. You do not need to lock any data that you are updating. Usually you would set FlushMode.MANUAL on an extended Session, so that only the last database transaction cycle is allowed to actually persist all modifications made in this conversation. Only this last database transaction will include the flush() operation, and then close() the session to end the conversation.

This pattern is problematic if the Session is too big to be stored during user think time (for example, an HttpSession should be kept as small as possible). As the Session is also the first-level cache and contains all loaded objects, we can probably use this strategy only for a few request/response cycles. Use a Session only for a single conversation as it will soon have stale data.

Keep the disconnected Session close to the persistence layer. Use an EJB stateful session bean to hold the Session in a three-tier environment. Do not transfer it to the web layer, or even serialize it to a separate tier, to store it in the HttpSession.

The extended session pattern, or session-per-conversation, is more difficult to implement with automatic current session context management. You need to supply your own implementation of the CurrentSessionContext for this. See the Hibernate Wiki for examples.

영속 저장소에 대한 각각의 상호작용은 새로운 Session에서 일어난다. 하지만 동일한 영속 인스턴스들은 데이터베이스와의 각각의 상호작용에 재사용된다. 어플리케이션은 원래 로드되었던 detached 인스턴스들의 상태를 또 다른 Session 내에서 처리하고 나서 Session.update()Session.saveOrUpdate()Session.merge()를 사용하여 그것들을 다시 첨부시킨다.

// foo is an instance loaded by a previous Session foo.setProperty("bar"); session = factory.openSession(); Transaction t = session.beginTransaction(); session.saveOrUpdate(foo); // Use merge() if "foo" might have been loaded already t.commit(); session.close();

Again, Hibernate will check instance versions during flush, throwing an exception if conflicting updates occurred.

You can also call lock() instead of update(), and use LockMode.READ (performing a version check and bypassing all caches) if you are sure that the object has not been modified.

You can disable Hibernate's automatic version increment for particular properties and collections by setting the optimistic-lock mapping attribute to false. Hibernate will then no longer increment versions if the property is dirty.

Legacy database schemas are often static and cannot be modified. Or, other applications might access the same database and will not know how to handle version numbers or even timestamps. In both cases, versioning cannot rely on a particular column in a table. To force a version check with a comparison of the state of all fields in a row but without a version or timestamp property mapping, turn on optimistic-lock="all" in the <class> mapping. This conceptually only works if Hibernate can compare the old and the new state (i.e., if you use a single long Session and not session-per-request-with-detached-objects).

Concurrent modification can be permitted in instances where the changes that have been made do not overlap. If you set optimistic-lock="dirty" when mapping the <class>, Hibernate will only compare dirty fields during flush.

In both cases, with dedicated version/timestamp columns or with a full/dirty field comparison, Hibernate uses a single UPDATE statement, with an appropriate WHERE clause, per entity to execute the version check and update the information. If you use transitive persistence to cascade reattachment to associated entities, Hibernate may execute unnecessary updates. This is usually not a problem, but on update triggers in the database might be executed even when no changes have been made to detached instances. You can customize this behavior by setting select-before-update="true" in the <class> mapping, forcing Hibernate to SELECT the instance to ensure that changes did occur before updating the row.

It is not intended that users spend much time worrying about locking strategies. It is usually enough to specify an isolation level for the JDBC connections and then simply let the database do all the work. However, advanced users may wish to obtain exclusive pessimistic locks or re-obtain locks at the start of a new transaction.

Hibernate will always use the locking mechanism of the database; it never lock objects in memory.

The LockMode class defines the different lock levels that can be acquired by Hibernate. A lock is obtained by the following mechanisms:

  • LockMode.WRITE는 Hibernate가 한 행을 업데이트 하거나 insert 할 때 자동적으로 획득된다.

  • LockMode.UPGRADE can be acquired upon explicit user request using SELECT ... FOR UPDATE on databases which support that syntax.

  • LockMode.UPGRADE_NOWAIT can be acquired upon explicit user request using a SELECT ... FOR UPDATE NOWAIT under Oracle.

  • LockMode.READ is acquired automatically when Hibernate reads data under Repeatable Read or Serializable isolation level. It can be re-acquired by explicit user request.

  • LockMode.NONE은 잠금이 없음을 나타낸다. 모든 객체들은 Transaction의 끝에서 이 잠금 모드로 전환된다. update() 또는 saveOrUpdate()에 대한 호출을 통해 세션과 연관된 객체들이 또한 이 잠금 모드로 시작된다.

"명시적인 사용자 요청"은 다음 방법들 중 하나로 표현된다:

  • LockMode를 지정한 Session.load()에 대한 호출.

  • Session.lock()에 대한 호출.

  • Query.setLockMode()에 대한 호출.

만일 Session.load()가 UPGRADE 또는 UPGRADE_NOWAIT 모드로 호출되고 ,요청된 객체가 아직 이 세션에 의해 로드되지 않았다면, 그 객체는 SELECT ... FOR UPDATE를 사용하여 로드된다. 만일 요청된 것이 아닌 다소 제한적인 잠금으로 이미 로드되어 있는 객체에 대해 load()가 호출될 경우, Hibernate는 그 객체에 대해 lock()을 호출한다.

Session.lock() performs a version number check if the specified lock mode is READUPGRADE or UPGRADE_NOWAIT. In the case of UPGRADE or UPGRADE_NOWAITSELECT ... FOR UPDATE is used.

If the requested lock mode is not supported by the database, Hibernate uses an appropriate alternate mode instead of throwing an exception. This ensures that applications are portable.

One of the legacies of Hibernate 2.x JDBC connection management meant that a Session would obtain a connection when it was first required and then maintain that connection until the session was closed. Hibernate 3.x introduced the notion of connection release modes that would instruct a session how to handle its JDBC connections. The following discussion is pertinent only to connections provided through a configured ConnectionProvider. User-supplied connections are outside the breadth of this discussion. The different release modes are identified by the enumerated values of org.hibernate.ConnectionReleaseMode:

  • ON_CLOSE: is the legacy behavior described above. The Hibernate session obtains a connection when it first needs to perform some JDBC access and maintains that connection until the session is closed.

  • AFTER_TRANSACTION: releases connections after a org.hibernate.Transaction has been completed.

  • AFTER_STATEMENT (also referred to as aggressive release): releases connections after every statement execution. This aggressive releasing is skipped if that statement leaves open resources associated with the given session. Currently the only situation where this occurs is through the use of org.hibernate.ScrollableResults.

The configuration parameter hibernate.connection.release_mode is used to specify which release mode to use. The possible values are as follows:

  • auto (the default): this choice delegates to the release mode returned by the org.hibernate.transaction.TransactionFactory.getDefaultReleaseMode() method. For JTATransactionFactory, this returns ConnectionReleaseMode.AFTER_STATEMENT; for JDBCTransactionFactory, this returns ConnectionReleaseMode.AFTER_TRANSACTION. Do not change this default behavior as failures due to the value of this setting tend to indicate bugs and/or invalid assumptions in user code.

  • on_close: uses ConnectionReleaseMode.ON_CLOSE. This setting is left for backwards compatibility, but its use is discouraged.

  • after_transaction: uses ConnectionReleaseMode.AFTER_TRANSACTION. This setting should not be used in JTA environments. Also note that with ConnectionReleaseMode.AFTER_TRANSACTION, if a session is considered to be in auto-commit mode, connections will be released as if the release mode were AFTER_STATEMENT.

  • after_statement: uses ConnectionReleaseMode.AFTER_STATEMENT. Additionally, the configured ConnectionProvider is consulted to see if it supports this setting (supportsAggressiveRelease()). If not, the release mode is reset to ConnectionReleaseMode.AFTER_TRANSACTION. This setting is only safe in environments where we can either re-acquire the same underlying JDBC connection each time you make a call into ConnectionProvider.getConnection() or in auto-commit environments where it does not matter if we re-establish the same connection.

It is useful for the application to react to certain events that occur inside Hibernate. This allows for the implementation of generic functionality and the extension of Hibernate functionality.

The Interceptor interface provides callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. One possible use for this is to track auditing information. For example, the following Interceptor automatically sets the createTimestamp when an Auditable is created and updates the lastUpdateTimestamp property when an Auditable is updated.

You can either implement Interceptor directly or extend EmptyInterceptor.

package org.hibernate.test; import java.io.Serializable; import java.util.Date; import java.util.Iterator; import org.hibernate.EmptyInterceptor; import org.hibernate.Transaction; import org.hibernate.type.Type; public class AuditInterceptor extends EmptyInterceptor { private int updates; private int creates; private int loads; public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { // do nothing } public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { if ( entity instanceof Auditable ) { updates++; for ( int i=0; i < propertyNames.length; i++ ) { if ( "lastUpdateTimestamp".equals( propertyNames[i] ) ) { currentState[i] = new Date(); return true; } } } return false; } public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if ( entity instanceof Auditable ) { loads++; } return false; } public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if ( entity instanceof Auditable ) { creates++; for ( int i=0; i<propertyNames.length; i++ ) { if ( "createTimestamp".equals( propertyNames[i] ) ) { state[i] = new Date(); return true; } } } return false; } public void afterTransactionCompletion(Transaction tx) { if ( tx.wasCommitted() ) { System.out.println("Creations: " + creates + ", Updates: " + updates, "Loads: " + loads); } updates=0; creates=0; loads=0; } }

There are two kinds of inteceptors: Session-scoped and SessionFactory-scoped.

Session-영역의 인터셉터는 세션이 하나의 Interceptor를 수용하는 오버로드된 SessionFactory.openSession() 메소드들 중 하나를 사용하여 열릴 때 지정된다.

Session session = sf.openSession( new AuditInterceptor() );

SessionFactory-scoped interceptor is registered with the Configuration object prior to building the SessionFactory. Unless a session is opened explicitly specifying the interceptor to use, the supplied interceptor will be applied to all sessions opened from that SessionFactorySessionFactory-scoped interceptors must be thread safe. Ensure that you do not store session-specific states, since multiple sessions will use this interceptor potentially concurrently.

new Configuration().setInterceptor( new AuditInterceptor() );

If you have to react to particular events in your persistence layer, you can also use the Hibernate3 event architecture. The event system can be used in addition, or as a replacement, for interceptors.

All the methods of the Session interface correlate to an event. You have a LoadEvent, a FlushEvent, etc. Consult the XML configuration-file DTD or the org.hibernate.event package for the full list of defined event types. When a request is made of one of these methods, the Hibernate Session generates an appropriate event and passes it to the configured event listeners for that type. Out-of-the-box, these listeners implement the same processing in which those methods always resulted. However, you are free to implement a customization of one of the listener interfaces (i.e., the LoadEvent is processed by the registered implementation of the LoadEventListener interface), in which case their implementation would be responsible for processing any load() requests made of the Session.

The listeners should be considered singletons. This means they are shared between requests, and should not save any state as instance variables.

A custom listener implements the appropriate interface for the event it wants to process and/or extend one of the convenience base classes (or even the default event listeners used by Hibernate out-of-the-box as these are declared non-final for this purpose). Custom listeners can either be registered programmatically through the Configuration object, or specified in the Hibernate configuration XML. Declarative configuration through the properties file is not supported. Here is an example of a custom load event listener:

public class MyLoadListener implements LoadEventListener { // this is the single method defined by the LoadEventListener interface public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType) throws HibernateException { if ( !MySecurity.isAuthorized( event.getEntityClassName(), event.getEntityId() ) ) { throw MySecurityException("Unauthorized access"); } } }

당신은 또한 디폴트 리스너에 덧붙여 그 리스너를 사용하도록 Hibernate에게 알려주는 구성 엔트리를 필요로 한다:

<hibernate-configuration> <session-factory> ... <event type="load"> <listener class="com.eg.MyLoadListener"/> <listener class="org.hibernate.event.def.DefaultLoadEventListener"/> </event> </session-factory> </hibernate-configuration>

Instead, you can register it programmatically:

Configuration cfg = new Configuration(); LoadEventListener[] stack = { new MyLoadListener(), new DefaultLoadEventListener() }; cfg.EventListeners().setLoadEventListeners(stack);

Listeners registered declaratively cannot share instances. If the same class name is used in multiple <listener/> elements, each reference will result in a separate instance of that class. If you need to share listener instances between listener types you must use the programmatic registration approach.

Why implement an interface and define the specific type during configuration? A listener implementation could implement multiple event listener interfaces. Having the type additionally defined during registration makes it easier to turn custom listeners on or off during configuration.

Usually, declarative security in Hibernate applications is managed in a session facade layer. Hibernate3 allows certain actions to be permissioned via JACC, and authorized via JAAS. This is an optional functionality that is built on top of the event architecture.

먼저, 당신은 JAAS authorization 사용을 이용 가능하도록 하기 위해 적절한 이벤트 리스터들을 구성해야 한다.

<listener type="pre-delete" class="org.hibernate.secure.JACCPreDeleteEventListener"/> <listener type="pre-update" class="org.hibernate.secure.JACCPreUpdateEventListener"/> <listener type="pre-insert" class="org.hibernate.secure.JACCPreInsertEventListener"/> <listener type="pre-load" class="org.hibernate.secure.JACCPreLoadEventListener"/>

Note that <listener type="..." class="..."/> is shorthand for <event type="..."><listener class="..."/></event> when there is exactly one listener for a particular event type.

Next, while still in hibernate.cfg.xml, bind the permissions to roles:

<grant role="admin" entity-name="User" actions="insert,update,read"/> <grant role="su" entity-name="User" actions="*"/>

역할(role) 이름들은 당신의 JACC 프로바이더에 의해 인지된 역할(role)들이다.

A naive approach to inserting 100,000 rows in the database using Hibernate might look like this:

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); } tx.commit(); session.close();

This would fall over with an OutOfMemoryException somewhere around the 50,000th row. That is because Hibernate caches all the newly inserted Customer instances in the session-level cache. In this chapter we will show you how to avoid this problem.

If you are undertaking batch processing you will need to enable the use of JDBC batching. This is absolutely essential if you want to achieve optimal performance. Set the JDBC batch size to a reasonable number (10-50, for example):

hibernate.jdbc.batch_size 20

Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.

You can also do this kind of work in a process where interaction with the second-level cache is completely disabled:

hibernate.cache.use_second_level_cache false

하지만 이것은 절대적으로 필요하지 않다. 왜냐하면 우리는 second-level 캐시와의 상호작용을 불가능하도록 하기 위해 명시적으로 CacheMode를 설정할 수 있기 때문이다.

Alternatively, Hibernate provides a command-oriented API that can be used for streaming data to and from the database in the form of detached objects. A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache. It does not implement transactional write-behind or automatic dirty checking. Operations performed using a stateless session never cascade to associated instances. Collections are ignored by a stateless session. Operations performed via a stateless session bypass Hibernate's event model and interceptors. Due to the lack of a first-level cache, Stateless sessions are vulnerable to data aliasing effects. A stateless session is a lower-level abstraction that is much closer to the underlying JDBC.

StatelessSession session = sessionFactory.openStatelessSession(); Transaction tx = session.beginTransaction(); ScrollableResults customers = session.getNamedQuery("GetCustomers") .scroll(ScrollMode.FORWARD_ONLY); while ( customers.next() ) { Customer customer = (Customer) customers.get(0); customer.updateStuff(...); session.update(customer); } tx.commit(); session.close();

In this code example, the Customer instances returned by the query are immediately detached. They are never associated with any persistence context.

The insert(), update() and delete() operations defined by the StatelessSession interface are considered to be direct database row-level operations. They result in the immediate execution of a SQL INSERT, UPDATE or DELETE respectively. They have different semantics to the save(), saveOrUpdate() and delete() operations defined by the Session interface.

As already discussed, automatic and transparent object/relational mapping is concerned with the management of the object state. The object state is available in memory. This means that manipulating data directly in the database (using the SQL Data Manipulation Language (DML) the statements: INSERTUPDATEDELETE) will not affect in-memory state. However, Hibernate provides methods for bulk SQL-style DML statement execution that is performed through the Hibernate Query Language (HQL).

The pseudo-syntax for UPDATE and DELETE statements is: ( UPDATE | DELETE ) FROM? EntityName (WHERE where_conditions)?.

Some points to note:

  • from-절에서, FROM 키워드는 옵션이다

  • There can only be a single entity named in the from-clause. It can, however, be aliased. If the entity name is aliased, then any property references must be qualified using that alias. If the entity name is not aliased, then it is illegal for any property references to be qualified.

  • No joins, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.

  • where-절 또한 옵션이다.

As an example, to execute an HQL UPDATE, use the Query.executeUpdate() method. The method is named for those familiar with JDBC's PreparedStatement.executeUpdate():

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName"; // or String hqlUpdate = "update Customer set name = :newName where name = :oldName"; int updatedEntities = s.createQuery( hqlUpdate ) .setString( "newName", newName ) .setString( "oldName", oldName ) .executeUpdate(); tx.commit(); session.close();

In keeping with the EJB3 specification, HQL UPDATE statements, by default, do not effect the version or the timestamp property values for the affected entities. However, you can force Hibernate to reset the version or timestamp property values through the use of a versioned update. This is achieved by adding the VERSIONED keyword after the UPDATE keyword.

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlVersionedUpdate = "update versioned Customer set name = :newName where name = :oldName"; int updatedEntities = s.createQuery( hqlUpdate ) .setString( "newName", newName ) .setString( "oldName", oldName ) .executeUpdate(); tx.commit(); session.close();

Custom version types, org.hibernate.usertype.UserVersionType, are not allowed in conjunction with a update versioned statement.

HQL DELETE를 실행하려면, 같은 메소드 Query.executeUpdate()를 사용하라:

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlDelete = "delete Customer c where c.name = :oldName"; // or String hqlDelete = "delete Customer where name = :oldName"; int deletedEntities = s.createQuery( hqlDelete ) .setString( "oldName", oldName ) .executeUpdate(); tx.commit(); session.close();

The int value returned by the Query.executeUpdate() method indicates the number of entities effected by the operation. This may or may not correlate to the number of rows effected in the database. An HQL bulk operation might result in multiple actual SQL statements being executed (for joined-subclass, for example). The returned number indicates the number of actual entities affected by the statement. Going back to the example of joined-subclass, a delete against one of the subclasses may actually result in deletes against not just the table to which that subclass is mapped, but also the "root" table and potentially joined-subclass tables further down the inheritance hierarchy.

장래의 배포본들에서 전달될 대량 HQL 오퍼레이션들에 대한 몇 가지 제한들이 현재 존재함을 노트하라; 상세한 것은 JIRA 로드맵을 참조하라. INSERT ë¬¸ìž¥ë“¤ì„ 위한 유사-구문은 다음과 같다: INSERT INTO EntityName properties_list select_statement. 노트할 몇 가지:

  • 오직 INSERT INTO ... SELECT ... 형식 만일 지원된다; INSERT INTO ... VALUES ... 형식은 지원되지 않는다.

    The properties_list is analogous to the column specification in the SQL INSERT statement. For entities involved in mapped inheritance, only properties directly defined on that given class-level can be used in the properties_list. Superclass properties are not allowed and subclass properties do not make sense. In other words, INSERT statements are inherently non-polymorphic.

  • select_statement can be any valid HQL select query, with the caveat that the return types must match the types expected by the insert. Currently, this is checked during query compilation rather than allowing the check to relegate to the database. This might, however, cause problems between Hibernate Types which are equivalent as opposed to equal. This might cause issues with mismatches between a property defined as a org.hibernate.type.DateType and a property defined as a org.hibernate.type.TimestampType, even though the database might not make a distinction or might be able to handle the conversion.

  • For the id property, the insert statement gives you two options. You can either explicitly specify the id property in the properties_list, in which case its value is taken from the corresponding select expression, or omit it from the properties_list, in which case a generated value is used. This latter option is only available when using id generators that operate in the database; attempting to use this option with any "in memory" type generators will cause an exception during parsing. For the purposes of this discussion, in-database generators are considered to be org.hibernate.id.SequenceGenerator (and its subclasses) and any implementers of org.hibernate.id.PostInsertIdentifierGenerator. The most notable exception here is org.hibernate.id.TableHiLoGenerator, which cannot be used because it does not expose a selectable way to get its values.

  • For properties mapped as either version or timestamp, the insert statement gives you two options. You can either specify the property in the properties_list, in which case its value is taken from the corresponding select expressions, or omit it from the properties_list, in which case the seed value defined by the org.hibernate.type.VersionType is used.

The following is an example of an HQL INSERT statement execution:

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ..."; int createdEntities = s.createQuery( hqlInsert ) .executeUpdate(); tx.commit(); session.close();

Hibernate uses a powerful query language (HQL) that is similar in appearance to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association.

With the exception of names of Java classes and properties, queries are case-insensitive. So SeLeCT is the same as sELEct is the same as SELECT, but org.hibernate.eg.FOO is not org.hibernate.eg.Foo, and foo.barSet is not foo.BARSET.

This manual uses lowercase HQL keywords. Some users find queries with uppercase keywords more readable, but this convention is unsuitable for queries embedded in Java code.

가장 간단한 가능한 Hibernate 질의는 다음 형식이다:

from eg.Cat

This returns all instances of the class eg.Cat. You do not usually need to qualify the class name, since auto-import is the default. For example:

from Cat

In order to refer to the Cat in other parts of the query, you will need to assign an alias. For example:

from Cat as cat

This query assigns the alias cat to Cat instances, so you can use that alias later in the query. The as keyword is optional. You could also write:

from Cat cat

Multiple classes can appear, resulting in a cartesian product or "cross" join.

from Formula, Parameter
from Formula as form, Parameter as param

It is good practice to name query aliases using an initial lowercase as this is consistent with Java naming standards for local variables (e.g. domesticCat).

You can also assign aliases to associated entities or to elements of a collection of values using a join. For example:

from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten
from Cat as cat left join cat.mate.kittens as kittens
from Formula form full join form.parameter param

The supported join types are borrowed from ANSI SQL:

inner joinleft outer join, 그리고 right outer join 구조체들이 약칭될 수 있다.

from Cat as cat join cat.mate as mate left join cat.kittens as kitten

당신은 HQL with 키워드를 사용하여 특별한 조인 조건들을 제공할 수 있다.

from Cat as cat left join cat.kittens as kitten with kitten.bodyWeight > 10.0

A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See 19.1절. “페칭 방도들” for more information.

from Cat as cat inner join fetch cat.mate left join fetch cat.kittens

A fetch join does not usually need to assign an alias, because the associated objects should not be used in the where clause (or any other clause). The associated objects are also not returned directly in the query results. Instead, they may be accessed via the parent object. The only reason you might need an alias is if you are recursively join fetching a further collection:

from Cat as cat inner join fetch cat.mate left join fetch cat.kittens child left join fetch child.kittens

The fetch construct cannot be used in queries called using iterate() (though scroll() can be used). Fetch should be used together with setMaxResults() or setFirstResult(), as these operations are based on the result rows which usually contain duplicates for eager collection fetching, hence, the number of rows is not what you would expect. Fetch should also not be used together with impromptu with condition. It is possible to create a cartesian product by join fetching more than one collection in a query, so take care in this case. Join fetching multiple collection roles can produce unexpected results for bag mappings, so user discretion is advised when formulating queries in this case. Finally, note that full join fetch and right join fetch are not meaningful.

If you are using property-level lazy fetching (with bytecode instrumentation), it is possible to force Hibernate to fetch the lazy properties in the first query immediately using fetch all properties.

from Document fetch all properties order by name
from Document doc fetch all properties where lower(doc.name) like '%cats%'

HQL은 두 가지 형식의 연관 조인을 지원한다: 암묵적 그리고 명시적.

The queries shown in the previous section all use the explicit form, that is, where the join keyword is explicitly used in the from clause. This is the recommended form.

함축적인 형식은 join 키워드를 사용하지 않는다. 대신에, 연관들은 dot(.) 표기를 사용하여 "dot-참조된다(dereferenced)". 함축적인 조인들은 임의의 HQL 절들내에 나타날 수 있다. 함축적인 join은 결과되는 SQL 문장에서 inner join으로 귀결된다.

from Cat as cat where cat.mate.name like '%s%'

There are 2 ways to refer to an entity's identifier property:

  • The special property (lowercase) id may be used to reference the identifier property of an entity provided that the entity does not define a non-identifier property named id.

  • If the entity defines a named identifier property, you can use that property name.

References to composite identifier properties follow the same naming rules. If the entity has a non-identifier property named id, the composite identifier property can only be referenced by its defined named. Otherwise, the special id property can be used to reference the identifier property.

The select clause picks which objects and properties to return in the query result set. Consider the following:

select mate from Cat as cat inner join cat.mate as mate

The query will select mates of other Cats. You can express this query more compactly as:

select cat.mate from Cat cat

Queries can return properties of any value type including properties of component type:

select cat.name from DomesticCat cat where cat.name like 'fri%'
select cust.name.firstName from Customer as cust

Queries can return multiple objects and/or properties as an array of type Object[]:

select mother, offspr, mate.name from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr

Or as a List:

select new list(mother, offspr, mate.name) from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr

Or - assuming that the class Family has an appropriate constructor - as an actual typesafe Java object:

select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr

You can assign aliases to selected expressions using as:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n from Cat cat

다음은 select new map과 함께 사용될 때 가장 유용하다:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n ) from Cat cat

이 질의는 select된 값들에 대한 alias로부터 한 개의 Map을 반환한다.

다음과 같은 질의:

from Cat as cat

returns instances not only of Cat, but also of subclasses like DomesticCat. Hibernate queries can name any Java class or interface in the from clause. The query will return instances of all persistent classes that extend that class or implement the interface. The following query would return all persistent objects:

from java.lang.Object o

인터페이스 Named는 여러 가지 영속 클래스들에 의해 구현될 수도 있다:

from Named n, Named m where n.name = m.name

These last two queries will require more than one SQL SELECT. This means that the order by clause does not correctly order the whole result set. It also means you cannot call these queries using Query.scroll().

The where clause allows you to refine the list of instances returned. If no alias exists, you can refer to properties by name:

from Cat where name='Fritz'

만일 한 개의 alias가 존재할 경우, 하나의 수식어가 붙은 프로퍼티 이름을 사용하라:

from Cat as cat where cat.name='Fritz'

This returns instances of Cat named 'Fritz'.

The following query:

select foo from Foo foo, Bar bar where foo.startDate = bar.date

returns all instances of Foo with an instance of bar with a date property equal to the startDate property of the Foo. Compound path expressions make the where clause extremely powerful. Consider the following:

from Cat cat where cat.mate.name is not null

This query translates to an SQL query with a table (inner) join. For example:

from Foo foo where foo.bar.baz.customer.address.city is not null

would result in a query that would require four table joins in SQL.

The = operator can be used to compare not only properties, but also instances:

from Cat cat, Cat rival where cat.mate = rival.mate
select cat, mate from Cat cat, Cat mate where cat.mate = mate

The special property (lowercase) id can be used to reference the unique identifier of an object. See 14.5절. “Referring to identifier property” for more information.

from Cat as cat where cat.id = 123 from Cat as cat where cat.mate.id = 69

The second query is efficient and does not require a table join.

Properties of composite identifiers can also be used. Consider the following example where Person has composite identifiers consisting of country and medicareNumber:

from bank.Person person where person.id.country = 'AU' and person.id.medicareNumber = 123456
from bank.Account account where account.owner.id.country = 'AU' and account.owner.id.medicareNumber = 123456

Once again, the second query does not require a table join.

See 14.5절. “Referring to identifier property” for more information regarding referencing identifier properties)

The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat

You can also use components or composite user types, or properties of said component types. See 14.17절. “컴포넌트들” for more information.

An "any" type has the special properties id and class that allows you to express a join in the following way (where AuditLog.item is a property mapped with <any>):

from AuditLog log, Payment payment where log.item.class = 'Payment' and log.item.id = payment.id

The log.item.class and payment.class would refer to the values of completely different database columns in the above query.

Expressions used in the where clause include the following:

in and between can be used as follows:

from DomesticCat cat where cat.name between 'A' and 'B'
from DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )

The negated forms can be written as follows:

from DomesticCat cat where cat.name not between 'A' and 'B'
from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )

Similarly, is null and is not null can be used to test for null values.

Booleans can be easily used in expressions by declaring HQL query substitutions in Hibernate configuration:

<property name="hibernate.query.substitutions">true 1, false 0</property>

이것은 키워드 true와 false 키워드들을 이 HQL로부터 번역된 SQL에서 리터럴 1과 0으로 대체될 것이다:

from Cat cat where cat.alive = true

You can test the size of a collection with the special property size or the special size() function.

from Cat cat where cat.kittens.size > 0
from Cat cat where size(cat.kittens) > 0

For indexed collections, you can refer to the minimum and maximum indices using minindex and maxindex functions. Similarly, you can refer to the minimum and maximum elements of a collection of basic type using the minelement and maxelement functions. For example:

from Calendar cal where maxelement(cal.holidays) > current_date
from Order order where maxindex(order.items) > 100
from Order order where minelement(order.items) > 10000

The SQL functions any, some, all, exists, in are supported when passed the element or index set of a collection (elements and indices functions) or the result of a subquery (see below):

select mother from Cat as mother, Cat as kit where kit in elements(foo.kittens)
select p from NameList list, Person p where p.name = some elements(list.names)
from Cat cat where exists elements(cat.kittens)
from Player p where 3 > all elements(p.scores)
from Show show where 'fizard' in indices(show.acts)

Note that these constructs - sizeelementsindicesminindexmaxindexminelementmaxelement - can only be used in the where clause in Hibernate3.

Elements of indexed collections (arrays, lists, and maps) can be referred to by index in a where clause only:

from Order order where order.items[0].id = 1234
select person from Person person, Calendar calendar where calendar.holidays['national day'] = person.birthDay and person.nationality.calendar = calendar
select item from Item item, Order order where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11
select item from Item item, Order order where order.items[ maxindex(order.items) ] = item and order.id = 11

The expression inside [] can even be an arithmetic expression:

select item from Item item, Order order where order.items[ size(order.items) - 1 ] = item

HQL also provides the built-in index() function for elements of a one-to-many association or collection of values.

select item, index(item) from Order order join order.items item where index(item) < 5

Scalar SQL functions supported by the underlying database can be used:

from DomesticCat cat where upper(cat.name) like 'FRI%'

Consider how much longer and less readable the following query would be in SQL:

select cust from Product prod, Store store inner join store.customers cust where prod.name = 'widget' and store.location.name in ( 'Melbourne', 'Sydney' ) and prod = all elements(cust.currentOrder.lineItems)

힌트 : 다음과 같은 어떤 것

SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order FROM customers cust, stores store, locations loc, store_customers sc, product prod WHERE prod.name = 'widget' AND store.loc_id = loc.id AND loc.name IN ( 'Melbourne', 'Sydney' ) AND sc.store_id = store.id AND sc.cust_id = cust.id AND prod.id = ALL( SELECT item.prod_id FROM line_items item, orders o WHERE item.order_id = o.id AND cust.current_order = o.id )

The list returned by a query can be ordered by any property of a returned class or components:

from DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate

asc 옵션 또는 desc 옵션은 각각 오름차순 또는 내림차순 정렬을 나타낸다.

A query that returns aggregate values can be grouped by any property of a returned class or components:

select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color
select foo.id, avg(name), max(name) from Foo foo join foo.names name group by foo.id

또한 having 절이 허용된다.

select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)

SQL functions and aggregate functions are allowed in the having and order by clauses if they are supported by the underlying database (i.e., not in MySQL).

select cat from Cat cat join cat.kittens kitten group by cat.id, cat.name, cat.other, cat.properties having avg(kitten.weight) > 100 order by count(kitten) asc, sum(kitten.weight) desc

Neither the group by clause nor the order by clause can contain arithmetic expressions. Hibernate also does not currently expand a grouped entity, so you cannot write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.

subselect들을 지원하는 데이터베이스들의 경우, Hibernate는 질의들 내에 서브질의들을 지원한다. 서브질의는 괄호로 묶여져야 한다(자주 SQL 집계함수 호출에 의해). 심지어 서로 상관된 서브질의들(외부 질의 내에서 alias를 참조하는 서브질의들)이 허용된다.

from Cat as fatcat where fatcat.weight > ( select avg(cat.weight) from DomesticCat cat )
from DomesticCat as cat where cat.name = some ( select name.nickName from Name as name )
from Cat as cat where not exists ( from Cat as mate where mate.mate = cat )
from DomesticCat as cat where cat.name not in ( select name.nickName from Name as name )
select cat.id, (select max(kit.weight) from cat.kitten kit) from Cat as cat

Note that HQL subqueries can occur only in the select or where clauses.

Note that subqueries can also utilize row value constructor syntax. See 14.18절. “Row value constructor 구문” for more information.

Hibernate queries can be quite powerful and complex. In fact, the power of the query language is one of Hibernate's main strengths. The following example queries are similar to queries that have been used on recent projects. Please note that most queries you will write will be much simpler than the following examples.

The following query returns the order id, number of items, the given minimum total value and the total value of the order for all unpaid orders for a particular customer. The results are ordered by total value. In determining the prices, it uses the current catalog. The resulting SQL query, against the ORDERORDER_LINEPRODUCTCATALOG and PRICE tables has four inner joins and an (uncorrelated) subselect.

select order.id, sum(price.amount), count(item) from Order as order join order.lineItems as item join item.product as product, Catalog as catalog join catalog.prices as price where order.paid = false and order.customer = :customer and price.product = product and catalog.effectiveDate < sysdate and catalog.effectiveDate >= all ( select cat.effectiveDate from Catalog as cat where cat.effectiveDate < sysdate ) group by order having sum(price.amount) > :minAmount order by sum(price.amount) desc

괴물 같은 것! 실제로 실 생활에서, 나는 서브질의들을 매우 좋아하지 않아서, 나의 질의는 실제로 다음과 같았다:

select order.id, sum(price.amount), count(item) from Order as order join order.lineItems as item join item.product as product, Catalog as catalog join catalog.prices as price where order.paid = false and order.customer = :customer and price.product = product and catalog = :currentCatalog group by order having sum(price.amount) > :minAmount order by sum(price.amount) desc

다음 질의는 현재 사용자에 의해 가장 최근의 상태 변경이 행해졌던 AWAITING_APPROVAL 상태에 있는 모든 지불들을 제외한, 각각의 상태에 있는 지불들의 개수를 카운트 한다. 그것은 PAYMENTPAYMENT_STATUSPAYMENT_STATUS_CHANGE 테이블들에 대한 두 개의 inner 조인들과 하나의 상관관계 지워진 subselect를 가진 SQL 질의로 변환된다.

select count(payment), status.name from Payment as payment join payment.currentStatus as status join payment.statusChanges as statusChange where payment.status.name <> PaymentStatus.AWAITING_APPROVAL or ( statusChange.timeStamp = ( select max(change.timeStamp) from PaymentStatusChange change where change.payment = payment ) and statusChange.user <> :currentUser ) group by status.name, status.sortOrder order by status.sortOrder

If the statusChanges collection was mapped as a list, instead of a set, the query would have been much simpler to write.

select count(payment), status.name from Payment as payment join payment.currentStatus as status where payment.status.name <> PaymentStatus.AWAITING_APPROVAL or payment.statusChanges[ maxIndex(payment.statusChanges) ].user <> :currentUser group by status.name, status.sortOrder order by status.sortOrder

다음 질의는 현재의 사용자가 속해 있는 조직의 모든 계정들과 지불되지 않은 지불들을 반환하는데 MS SQL Server isNull() 함수를 사용한다. 그것은 ACCOUNTPAYMENTPAYMENT_STATUSACCOUNT_TYPEORGANIZATIONORG_USER 테이블들에 대한 세 개의 inner 조인들, 하나의 outer 조인, 그리고 하나의 subselect를 가진 한 개의 SQL 질의로 번역된다.

select account, payment from Account as account left outer join account.payments as payment where :currentUser in elements(account.holder.users) and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID) order by account.type.sortOrder, account.accountNumber, payment.dueDate

몇몇 데이터베이스들의 경우, 우리는 (상관관계 지워진) subselect를 없앨 필요가 있을 것이다.

select account, payment from Account as account join account.holder.users as user left outer join account.payments as payment where :currentUser = user and PaymentStatus.UNPAID = isNull(payment.currentStatus.name, PaymentStatus.UNPAID) order by account.type.sortOrder, account.accountNumber, payment.dueDate

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

콜렉션의 크기에 따라 결과를 순서(ordering)지우려면, 다음 질의를 사용하라:

select usr.id, usr.name from User as usr left join usr.messages as msg group by usr.id, usr.name order by count(msg)

만일 당신의 데이터베이스가 subselect들을 지원할 경우, 당신은 당신의 질의의 where 절 내에 selection 사이즈에 대한 조건을 위치지울 수 있다:

from User usr where size(usr.messages) >= 1

If your database does not support subselects, use the following query:

select usr.id, usr.name from User usr.name join usr.messages msg group by usr.id, usr.name having count(msg) >= 1

As this solution cannot return a User with zero messages because of the inner join, the following form is also useful:

select usr.id, usr.name from User as usr left join usr.messages as msg group by usr.id, usr.name having count(msg) = 0

하나의 JavaBean의 프로퍼티들은 명명된 질의 파라미터들에 바인드될 수 있다:

Query q = s.createQuery("from foo Foo as foo where foo.name=:name and foo.size=:size"); q.setProperties(fooBean); // fooBean has getName() and getSize() List foos = q.list();

콜렉션들은 필터를 가진 Query 인터페이스를 사용하여 쪼매김하는 것이 가능하다:

Query q = s.createFilter( collection, "" ); // the trivial filter q.setMaxResults(PAGE_SIZE); q.setFirstResult(PAGE_SIZE * pageNumber); List page = q.list();

Collection elements can be ordered or grouped using a query filter:

Collection orderedCollection = s.filter( collection, "order by this.amount" ); Collection counts = s.filter( collection, "select this.type, count(this) group by this.type" );

당신은 콜렉션을 초기화 하지 않고서 그것(콜렉션)의 크기를 찾을 수 있다:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue();

Components can be used similarly to the simple value types that are used in HQL queries. They can appear in the select clause as follows:

select p.name from Person p
select p.name.first from Person p

여기서 Person의 name 속성은 컴포넌트이다. 컴포넌트들은 또한 where 절 내에 사용될 수 있다:

from Person p where p.name = :name
from Person p where p.name.first = :firstName

컴포넌트들은 또한 order by 절 내에 사용될 수 있다:

from Person p order by p.name
from Person p order by p.name.first

컴포넌트들에 대한 또 다른 공통적인 사용은 14.18절. “Row value constructor 구문”에 있다.

HQL supports the use of ANSI SQL row value constructor syntax, sometimes referred to AS tuple syntax, even though the underlying database may not support that notion. Here, we are generally referring to multi-valued comparisons, typically associated with components. Consider an entity Person which defines a name component:

from Person p where p.name.first='John' and p.name.last='Jingleheimer-Schmidt'

That is valid syntax although it is a little verbose. You can make this more concise by using row value constructor syntax:

from Person p where p.name=('John', 'Jingleheimer-Schmidt')

select절 내에 이것을 지정하는 것이 또한 유용할 수 있다:

select p.name from Person p

Using row value constructor syntax can also be beneficial when using subqueries that need to compare against multiple values:

from Cat as cat where not ( cat.name, cat.color ) in ( select cat.name, cat.color from DomesticCat cat )

One thing to consider when deciding if you want to use this syntax, is that the query will be dependent upon the ordering of the component sub-properties in the metadata.

Hibernate는 직관적인, 확장 가능한 criteria query API를 특징 짓는다.

org.hibernate.Criteria인터페이스는 특정 영속 클래스에 대한 질의를 표현한다. Session은 Criteria 인스턴스들에 대한 팩토리이다.

Criteria crit = sess.createCriteria(Cat.class); crit.setMaxResults(50); List cats = crit.list();

개별적인 질의 기준은 org.hibernate.criterion.Criterion 인터페이스의 인스턴스이다. org.hibernate.criterion.Restrictions 클래스는 어떤 미리 만들어진 Criterion 타입들을 얻는 팩토리 메소드들을 정의한다.

List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "Fritz%") ) .add( Restrictions.between("weight", minWeight, maxWeight) ) .list();

Restrictions can be grouped logically.

List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "Fritz%") ) .add( Restrictions.or( Restrictions.eq( "age", new Integer(0) ), Restrictions.isNull("age") ) ) .list();
List cats = sess.createCriteria(Cat.class) .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) ) .add( Restrictions.disjunction() .add( Restrictions.isNull("age") ) .add( Restrictions.eq("age", new Integer(0) ) ) .add( Restrictions.eq("age", new Integer(1) ) ) .add( Restrictions.eq("age", new Integer(2) ) ) ) ) .list();

There are a range of built-in criterion types (Restrictions subclasses). One of the most useful allows you to specify SQL directly.

List cats = sess.createCriteria(Cat.class) .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) ) .list();

질의된 엔티티의 행 alias에 의해 대체된 {alias} placeholder.

You can also obtain a criterion from a Property instance. You can create a Property by calling Property.forName():

Property age = Property.forName("age"); List cats = sess.createCriteria(Cat.class) .add( Restrictions.disjunction() .add( age.isNull() ) .add( age.eq( new Integer(0) ) ) .add( age.eq( new Integer(1) ) ) .add( age.eq( new Integer(2) ) ) ) ) .add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) ) .list();

By navigating associations using createCriteria() you can specify constraints upon related entities:

List cats = sess.createCriteria(Cat.class) .add( Restrictions.like("name", "F%") ) .createCriteria("kittens") .add( Restrictions.like("name", "F%") ) .list();

The second createCriteria() returns a new instance of Criteria that refers to the elements of the kittens collection.

There is also an alternate form that is useful in certain circumstances:

List cats = sess.createCriteria(Cat.class) .createAlias("kittens", "kt") .createAlias("mate", "mt") .add( Restrictions.eqProperty("kt.name", "mt.name") ) .list();

(createAlias()는 Criteria의 새로운 인스턴스를 생성시키지 않는다.)

The kittens collections held by the Cat instances returned by the previous two queries are not pre-filtered by the criteria. If you want to retrieve just the kittens that match the criteria, you must use a ResultTransformer.

List cats = sess.createCriteria(Cat.class) .createCriteria("kittens", "kt") .add( Restrictions.eq("name", "F%") ) .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) .list(); Iterator iter = cats.iterator(); while ( iter.hasNext() ) { Map map = (Map) iter.next(); Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS); Cat kitten = (Cat) map.get("kt"); }

org.hibernate.criterion.Example 클래스는 주어진 인스턴스로부터 질의 기준(criterion)을 구조화 시키는 것을 당신에게 허용해준다.

Cat cat = new Cat(); cat.setSex('F'); cat.setColor(Color.BLACK); List results = session.createCriteria(Cat.class) .add( Example.create(cat) ) .list();

버전 프로퍼티들, 식별자들, 연관관계들이 무시된다. 디폴트로 null 값 프로퍼티들이 제외된다.

당신은 Example이 적용되는 방법을 조정할 수 있다.

Example example = Example.create(cat) .excludeZeroes() //exclude zero valued properties .excludeProperty("color") //exclude the property named "color" .ignoreCase() //perform case insensitive string comparisons .enableLike(); //use like for string comparisons List results = session.createCriteria(Cat.class) .add(example) .list();

당신은 연관된 객체들에 대한 criteria(기준)을 위치지우는데 examples를 사용할 수 있다.

List results = session.createCriteria(Cat.class) .add( Example.create(cat) ) .createCriteria("mate") .add( Example.create( cat.getMate() ) ) .list();

The class org.hibernate.criterion.Projections is a factory for Projection instances. You can apply a projection to a query by calling setProjection().

List results = session.createCriteria(Cat.class) .setProjection( Projections.rowCount() ) .add( Restrictions.eq("color", Color.BLACK) ) .list();
List results = session.createCriteria(Cat.class) .setProjection( Projections.projectionList() .add( Projections.rowCount() ) .add( Projections.avg("weight") ) .add( Projections.max("weight") ) .add( Projections.groupProperty("color") ) ) .list();

criteria 질의 내에서는 명시적인 "group by"가 필수적이지 않다. 어떤 projection 타입들은 grouping projections들이게끔 정의되고, 그것은 또한 SQL group by 절 속에 나타난다.

An alias can be assigned to a projection so that the projected value can be referred to in restrictions or orderings. Here are two different ways to do this:

List results = session.createCriteria(Cat.class) .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) ) .addOrder( Order.asc("colr") ) .list();
List results = session.createCriteria(Cat.class) .setProjection( Projections.groupProperty("color").as("colr") ) .addOrder( Order.asc("colr") ) .list();

alias() 메소드와 as() 메소드는 또 다른 alias 된 Projection의 인스턴스 내에 하나의 projection 인스턴스를 간단하게 포장한다. 지름길로서, 당신이 projection을 projection 리스트에 추가할 때 당신은 alias를 할당할 수 있다:

List results = session.createCriteria(Cat.class) .setProjection( Projections.projectionList() .add( Projections.rowCount(), "catCountByColor" ) .add( Projections.avg("weight"), "avgWeight" ) .add( Projections.max("weight"), "maxWeight" ) .add( Projections.groupProperty("color"), "color" ) ) .addOrder( Order.desc("catCountByColor") ) .addOrder( Order.desc("avgWeight") ) .list();
List results = session.createCriteria(Domestic.class, "cat") .createAlias("kittens", "kit") .setProjection( Projections.projectionList() .add( Projections.property("cat.name"), "catName" ) .add( Projections.property("kit.name"), "kitName" ) ) .addOrder( Order.asc("catName") ) .addOrder( Order.asc("kitName") ) .list();

당신은 또한 projection들을 표현하는데 Property.forName()을 사용할 수 있다:

List results = session.createCriteria(Cat.class) .setProjection( Property.forName("name") ) .add( Property.forName("color").eq(Color.BLACK) ) .list();
List results = session.createCriteria(Cat.class) .setProjection( Projections.projectionList() .add( Projections.rowCount().as("catCountByColor") ) .add( Property.forName("weight").avg().as("avgWeight") ) .add( Property.forName("weight").max().as("maxWeight") ) .add( Property.forName("color").group().as("color" ) ) .addOrder( Order.desc("catCountByColor") ) .addOrder( Order.desc("avgWeight") ) .list();

For most queries, including criteria queries, the query cache is not efficient because query cache invalidation occurs too frequently. However, there is a special kind of query where you can optimize the cache invalidation algorithm: lookups by a constant natural key. In some applications, this kind of query occurs frequently. The criteria API provides special provision for this use case.

First, map the natural key of your entity using <natural-id> and enable use of the second-level cache.

<class name="User"> <cache usage="read-write"/> <id name="id"> <generator class="increment"/> </id> <natural-id> <property name="name"/> <property name="org"/> </natural-id> <property name="password"/> </class>

This functionality is not intended for use with entities with mutable natural keys.

Once you have enabled the Hibernate query cache, the Restrictions.naturalId() allows you to make use of the more efficient cache algorithm.

session.createCriteria(User.class) .add( Restrictions.naturalId() .set("name", "gavin") .set("org", "hb") ).setCacheable(true) .uniqueResult();

You can also express queries in the native SQL dialect of your database. This is useful if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate.

Hibernate3 allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Execution of native SQL queries is controlled via the SQLQuery interface, which is obtained by calling Session.createSQLQuery(). The following sections describe how to use this API for querying.

가장 기본적인 SQL 질의는 스칼라들(값들)의 목록을 얻는 것이다.

sess.createSQLQuery("SELECT * FROM CATS").list(); sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").list();

These will return a List of Object arrays (Object[]) with scalar values for each column in the CATS table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():

sess.createSQLQuery("SELECT * FROM CATS") .addScalar("ID", Hibernate.LONG) .addScalar("NAME", Hibernate.STRING) .addScalar("BIRTHDATE", Hibernate.DATE)

이 질의는 다음을 지정했다:

  • SQL 질의 문자열

  • 반환할 컬럼들과 타입들

This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get the ID, NAME and BIRTHDATE column as respectively a Long, String and a Short from the underlying resultset. This also means that only these three columns will be returned, even though the query is using * and could return more than the three listed columns.

스칼라들 중 몇몇 또는 전부에 대한 타입 정보를 남겨두는 것이 가능하다.

sess.createSQLQuery("SELECT * FROM CATS") .addScalar("ID", Hibernate.LONG) .addScalar("NAME") .addScalar("BIRTHDATE")

This is essentially the same query as before, but now ResultSetMetaData is used to determine the type of NAME and BIRTHDATE, where as the type of ID is explicitly specified.

How the java.sql.Types returned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. If a specific type is not mapped, or does not result in the expected type, it is possible to customize it via calls to registerHibernateType in the Dialect.

위의 질의들은 스칼라 값들을 반환하는 것, 결과셋들로부터 "원래의" 값들을 기본적으로 반환하는 것에 대한 전부였다. 다음은 addEntity()를 통해 native sql 질의로부터 엔티티 객체들을 얻는 방법을 보여준다.

sess.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class); sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);

이 질의는 다음을 지정했다:

  • SQL 질의 문자열

  • 그 질의에 의해 반환되는 엔티티

Cat이 컬럼 ID, NAME 그리고 BIRTHDATE로서 매핑된다고 가정하면, 위의 질의들은 둘다 각각의 요소가 하나의 Cat 엔티티인 하나의 List를 반환할 것이다.

만일 그 엔티티가 또 다른 엔티티에 대해 many-to-one로 매핑되어 있다면 또한 native 질의를 실행할 때 이것을 반환하는 것이 필수적고, 그 밖의 경우 데이터베이스 지정적인 "컬럼이 발견되지 않았습니다" 오류가 일어날 것이다. 추가적인 컬럼은 * 표기를 사용할 자동적으로 반환될 것이지만, 우리는 다음 Dog에 대한 many-to-one 예제에서처럼 명시적인 것을 더 선호한다:

sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE, DOG_ID FROM CATS").addEntity(Cat.class);

이것은 cat.getDog()이 고유하게 기능하는 것을 허용한다.

프락시를 초기화 시킴에 있어 가능한 특별한 라운드트립을 피하기 위해서 Dog에서 eagerly join시키는 것이 간으하다. 이것은 addJoin() 메소드를 통해 행해지는데, 그것은 연관이나 콜렉션 내에서 조인시키는 것을 당신에게 허용해준다.

sess.createSQLQuery("SELECT c.ID, NAME, BIRTHDATE, DOG_ID, D_ID, D_NAME FROM CATS c, DOGS d WHERE c.DOG_ID = d.D_ID") .addEntity("cat", Cat.class) .addJoin("cat.dog");

In this example, the returned Cat's will have their dog property fully initialized without any extra roundtrip to the database. Notice that you added an alias name ("cat") to be able to specify the target property path of the join. It is possible to do the same eager joining for collections, e.g. if the Cat had a one-to-many to Dog instead.

sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE, D_ID, D_NAME, CAT_ID FROM CATS c, DOGS d WHERE c.ID = d.CAT_ID") .addEntity("cat", Cat.class) .addJoin("cat.dogs");

At this stage you are reaching the limits of what is possible with native queries, without starting to enhance the sql queries to make them usable in Hibernate. Problems can arise when returning multiple entities of the same type or when the default alias/column names are not enough.

Until now, the result set column names are assumed to be the same as the column names specified in the mapping document. This can be problematic for SQL queries that join multiple tables, since the same column names can appear in more than one table.

컬럼 alias 주입은 다음 질의(아마 실패할 것이다)에서 필요하다:

sess.createSQLQuery("SELECT c.*, m.* FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID") .addEntity("cat", Cat.class) .addEntity("mother", Cat.class)

The query was intended to return two Cat instances per row: a cat and its mother. The query will, however, fail because there is a conflict of names; the instances are mapped to the same column names. Also, on some databases the returned column aliases will most likely be on the form "c.ID", "c.NAME", etc. which are not equal to the columns specified in the mappings ("ID" and "NAME").

다음 형식은 컬럼 이름 중복 취약점을 갖지 않는다:

sess.createSQLQuery("SELECT {cat.*}, {mother.*} FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID") .addEntity("cat", Cat.class) .addEntity("mother", Cat.class)

이 질의는 다음을 지정했다:

  • 컬럼 alias들을 주입하기 위한 Hibernate용 placeholder들을 가진 SQL 질의 문자열

  • 그 질의에 의해 반환되는 엔티티들

The {cat.*} and {mother.*} notation used above is a shorthand for "all properties". Alternatively, you can list the columns explicitly, but even in this case Hibernate injects the SQL column aliases for each property. The placeholder for a column alias is just the property name qualified by the table alias. In the following example, you retrieve Cats and their mothers from a different table (cat_log) to the one declared in the mapping metadata. You can even use the property aliases in the where clause.

String sql = "SELECT ID as {c.id}, NAME as {c.name}, " + "BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " + "FROM CAT_LOG c, CAT_LOG m WHERE {c.mother} = c.ID"; List loggedCats = sess.createSQLQuery(sql) .addEntity("cat", Cat.class) .addEntity("mother", Cat.class).list()

It is possible to apply a ResultTransformer to native SQL queries, allowing it to return non-managed entities.

sess.createSQLQuery("SELECT NAME, BIRTHDATE FROM CATS") .setResultTransformer(Transformers.aliasToBean(CatDTO.class))

이 질의는 다음을 지정했다:

  • SQL 질의 문자열

  • 결과 변환자(transformer)

위의 질의는 초기화되어 있고 NAME과 BIRTHNAME의 값들을 CatDTO의 대응하는 프로퍼티들과 필드들 속으로 주입시킨 CatDTO의 리스트를 반환할 것이다.

Native SQL queries which query for entities that are mapped as part of an inheritance must include all properties for the baseclass and all its subclasses.

Named SQL queries can be defined in the mapping document and called in exactly the same way as a named HQL query. In this case, you do not need to call addEntity().

<sql-query name="persons"> <return alias="person" class="eg.Person"/> SELECT person.NAME AS {person.name}, person.AGE AS {person.age}, person.SEX AS {person.sex} FROM PERSON person WHERE person.NAME LIKE :namePattern </sql-query>
List people = sess.getNamedQuery("persons") .setString("namePattern", namePattern) .setMaxResults(50) .list();

The <return-join> element is use to join associations and the <load-collection> element is used to define queries which initialize collections,

<sql-query name="personsWith"> <return alias="person" class="eg.Person"/> <return-join alias="address" property="person.mailingAddress"/> SELECT person.NAME AS {person.name}, person.AGE AS {person.age}, person.SEX AS {person.sex}, address.STREET AS {address.street}, address.CITY AS {address.city}, address.STATE AS {address.state}, address.ZIP AS {address.zip} FROM PERSON person JOIN ADDRESS address ON person.ID = address.PERSON_ID AND address.TYPE='MAILING' WHERE person.NAME LIKE :namePattern </sql-query>

명명된 SQL 질의는 스칼라 값을 반환할수도 있다. 당신은 <return-scalar> 요소를 사용하여 컬럼 alias와 Hibernate 타입을 선언해야 한다:

<sql-query name="mySqlQuery"> <return-scalar column="name" type="string"/> <return-scalar column="age" type="long"/> SELECT p.NAME AS name, p.AGE AS age, FROM PERSON p WHERE p.NAME LIKE 'Hiber%' </sql-query>

You can externalize the resultset mapping information in a <resultset> element which will allow you to either reuse them across several named queries or through the setResultSetMapping() API.

<resultset name="personAddress"> <return alias="person" class="eg.Person"/> <return-join alias="address" property="person.mailingAddress"/> </resultset> <sql-query name="personsWith" resultset-ref="personAddress"> SELECT person.NAME AS {person.name}, person.AGE AS {person.age}, person.SEX AS {person.sex}, address.STREET AS {address.street}, address.CITY AS {address.city}, address.STATE AS {address.state}, address.ZIP AS {address.zip} FROM PERSON person JOIN ADDRESS address ON person.ID = address.PERSON_ID AND address.TYPE='MAILING' WHERE person.NAME LIKE :namePattern </sql-query>

You can, alternatively, use the resultset mapping information in your hbm files directly in java code.

List cats = sess.createSQLQuery( "select {cat.*}, {kitten.*} from cats cat, cats kitten where kitten.mother = cat.id" ) .setResultSetMapping("catAndKitten") .list();

You can explicitly tell Hibernate what column aliases to use with <return-property>, instead of using the {}-syntax to let Hibernate inject its own aliases.For example:

<sql-query name="mySqlQuery"> <return alias="person" class="eg.Person"> <return-property name="name" column="myName"/> <return-property name="age" column="myAge"/> <return-property name="sex" column="mySex"/> </return> SELECT person.NAME AS myName, person.AGE AS myAge, person.SEX AS mySex, FROM PERSON person WHERE person.NAME LIKE :name </sql-query>

<return-property> also works with multiple columns. This solves a limitation with the {}-syntax which cannot allow fine grained control of multi-column properties.

<sql-query name="organizationCurrentEmployments"> <return alias="emp" class="Employment"> <return-property name="salary"> <return-column name="VALUE"/> <return-column name="CURRENCY"/> </return-property> <return-property name="endDate" column="myEndDate"/> </return> SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer}, STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate}, REGIONCODE as {emp.regionCode}, EID AS {emp.id}, VALUE, CURRENCY FROM EMPLOYMENT WHERE EMPLOYER = :id AND ENDDATE IS NULL ORDER BY STARTDATE ASC </sql-query>

In this example <return-property> was used in combination with the {}-syntax for injection. This allows users to choose how they want to refer column and properties.

만일 당신의 매핑이 한 개의 판별자(discriminator )를 가질 경우 당신은 판별자 컬럼을 지정하는데 <return-discriminator>를 사용해야 한다.

Hibernate3 provides support for queries via stored procedures and functions. Most of the following documentation is equivalent for both. The stored procedure/function must return a resultset as the first out-parameter to be able to work with Hibernate. An example of such a stored function in Oracle 9 and higher is as follows:

CREATE OR REPLACE FUNCTION selectAllEmployments RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR; BEGIN OPEN st_cursor FOR SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE, REGIONCODE, EID, VALUE, CURRENCY FROM EMPLOYMENT; RETURN st_cursor; END;

Hibernate에서 이 질의를 사용하기 위해 당신은 하나의 명명된 질의(a named query)를 통해 그것을 매핑할 필요가 있다.

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="Employment"> <return-property name="employee" column="EMPLOYEE"/> <return-property name="employer" column="EMPLOYER"/> <return-property name="startDate" column="STARTDATE"/> <return-property name="endDate" column="ENDDATE"/> <return-property name="regionCode" column="REGIONCODE"/> <return-property name="id" column="EID"/> <return-property name="salary"> <return-column name="VALUE"/> <return-column name="CURRENCY"/> </return-property> </return> { ? = call selectAllEmployments() } </sql-query>

Stored procedures currently only return scalars and entities. <return-join> and <load-collection> are not supported.

You cannot use stored procedures with Hibernate unless you follow some procedure/function rules. If they do not follow those rules they are not usable with Hibernate. If you still want to use these procedures you have to execute them via session.connection(). The rules are different for each database, since database vendors have different stored procedure semantics/syntax.

Stored procedure queries cannot be paged with setFirstResult()/setMaxResults().

The recommended call form is standard SQL92: { ? = call functionName(<parameters>) } or { ? = call procedureName(<parameters>}. Native call syntax is not supported.

Oracle의 경우 다음 규칙들이 적용된다:

  • A function must return a result set. The first parameter of a procedure must be an OUT that returns a result set. This is done by using a SYS_REFCURSOR type in Oracle 9 or 10. In Oracle you need to define a REF CURSOR type. See Oracle literature for further information.

Sybase 또는 MS SQL server의 경우 다음 규칙들이 적용된다:

  • The procedure must return a result set. Note that since these servers can return multiple result sets and update counts, Hibernate will iterate the results and take the first result that is a result set as its return value. Everything else will be discarded.

  • 만일 당신이 당신의 프로시저 내에 SET NOCOUNT ON을 이용 가능하게 할 수 있다면 그것은 아마 보다 효율적이게 될 것이지만 이것은 필요 조건이 아니다.

Hibernate3는 create, update, delete 오퍼레이션들을 위한 맞춤형 문장들을 사용할 수 있다. Hibernate에서 클래스와 콜렉션 영속자들은 구성 시에 생성된 문자열들의 집합(insertsql, deletesql, updatesql 등)을 이미 포함하고 있다. <sql-insert><sql-delete><sql-update> 매핑 태그들은 이들 문자열들을 오버라이드 시킨다:

<class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <sql-insert>INSERT INTO PERSON (NAME, ID) VALUES ( UPPER(?), ? )</sql-insert> <sql-update>UPDATE PERSON SET NAME=UPPER(?) WHERE ID=?</sql-update> <sql-delete>DELETE FROM PERSON WHERE ID=?</sql-delete> </class>

The SQL is directly executed in your database, so you can use any dialect you like. This will reduce the portability of your mapping if you use database specific SQL.

만일 callable 속성이 설정되면 내장 프로시저들이 지원된다:

<class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <sql-insert callable="true">{call createPerson (?, ?)}</sql-insert> <sql-delete callable="true">{? = call deletePerson (?)}</sql-delete> <sql-update callable="true">{? = call updatePerson (?, ?)}</sql-update> </class>

The order of the positional parameters is vital, as they must be in the same sequence as Hibernate expects them.

You can view the expected order by enabling debug logging for the org.hibernate.persister.entity level. With this level enabled, Hibernate will print out the static SQL that is used to create, update, delete etc. entities. To view the expected sequence, do not include your custom SQL in the mapping files, as this will override the Hibernate generated static SQL.

The stored procedures are in most cases required to return the number of rows inserted, updated and deleted, as Hibernate has some runtime checks for the success of the statement. Hibernate always registers the first statement parameter as a numeric output parameter for the CUD operations:

CREATE OR REPLACE FUNCTION updatePerson (uid IN NUMBER, uname IN VARCHAR2) RETURN NUMBER IS BEGIN update PERSON set NAME = uname, where ID = uid; return SQL%ROWCOUNT; END updatePerson;

Hibernate3 provides an innovative new approach to handling data with "visibility" rules. A Hibernate filter is a global, named, parameterized filter that can be enabled or disabled for a particular Hibernate session.

Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows you to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application.

필터들을 사용하기 위해서, 그것들은 먼저 정의되고 나서 적절한 매핑 요소들에 첨가되어야 한다. 필터를 정의하기 위해, <hibernate-mapping/> 요소 내부에 <filter-def/> 요소를 사용하라:

<filter-def name="myFilter"> <filter-param name="myFilterParam" type="string"/> </filter-def>

This filter can then be attached to a class:

<class name="myClass" ...> ... <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </class>

Or, to a collection:

<set ...> <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </set>

Or, to both or multiples of each at the same time.

The methods on Session are: enableFilter(String filterName)getEnabledFilter(String filterName), and disableFilter(String filterName). By default, filters are not enabled for a given session. Filters must be enabled through use of the Session.enableFilter() method, which returns an instance of the Filter interface. If you used the simple filter defined above, it would look like this:

session.enableFilter("myFilter").setParameter("myFilterParam", "some-value");

Methods on the org.hibernate.Filter interface do allow the method-chaining common to much of Hibernate.

The following is a full example, using temporal data with an effective record date pattern:

<filter-def name="effectiveDate"> <filter-param name="asOfDate" type="date"/> </filter-def> <class name="Employee" ...> ... <many-to-one name="department" column="dept_id" class="Department"/> <property name="effectiveStartDate" type="date" column="eff_start_dt"/> <property name="effectiveEndDate" type="date" column="eff_end_dt"/> ... <!-- Note that this assumes non-terminal records have an eff_end_dt set to a max db date for simplicity-sake --> <filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> </class> <class name="Department" ...> ... <set name="employees" lazy="true"> <key column="dept_id"/> <one-to-many class="Employee"/> <filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> </set> </class>

In order to ensure that you are provided with currently effective records, enable the filter on the session prior to retrieving employee data:

Session session = ...; session.enableFilter("effectiveDate").setParameter("asOfDate", new Date()); List results = session.createQuery("from Employee as e where e.salary > :targetSalary") .setLong("targetSalary", new Long(1000000)) .list();

Even though a salary constraint was mentioned explicitly on the results in the above HQL, because of the enabled filter, the query will return only currently active employees who have a salary greater than one million dollars.

If you want to use filters with outer joining, either through HQL or load fetching, be careful of the direction of the condition expression. It is safest to set this up for left outer joining. Place the parameter first followed by the column name(s) after the operator.

After being defined, a filter might be attached to multiple entities and/or collections each with its own condition. This can be problematic when the conditions are the same each time. Using <filter-def/> allows you to definine a default condition, either as an attribute or CDATA:

<filter-def name="myFilter" condition="abc > xyz">...</filter-def> <filter-def name="myOtherFilter">abc=xyz</filter-def>

This default condition will be used whenever the filter is attached to something without specifying a condition. This means you can give a specific condition as part of the attachment of the filter that overrides the default condition in that particular case.

XML Mapping is an experimental feature in Hibernate 3.0 and is currently under active development.

Hibernate allows you to work with persistent XML data in much the same way you work with persistent POJOs. A parsed XML tree can be thought of as another way of representing the relational data at the object level, instead of POJOs.

Hibernate는 XML 트리들을 처리하는 API로서 dom4j를 지원한다. 당신은 데이터베이스로부터 dom4j 트리들을 검색하고 당신이 그 트리를 데이터베이스와 자동적으로 동기화시키기 위해 어떤 변경을 행하도록 하는 질의들을 작성할 수 있다. 당신은 심지어 XML 문서를 취하고, dom4j를 사용하여 그것을 파싱하고, Hibernate의 다음 기본적인 오퍼레이션들 중 어떤 것으로서 그것을 데이터베이스에 저장시킬 수 있다: persist(), saveOrUpdate(), merge(), delete(), replicate()(merging(병합)은 아직 지원되지 않는다).

이 특징은 데이터 가져오기/내보내기,JMS 또는 SOAP 그리고 XSLT-기반의 레포팅을 통한 엔티티 데이터의 구체화를 포함하는 많은 어플리케이션들을 갖는다.

A single mapping can be used to simultaneously map properties of a class and nodes of an XML document to the database, or, if there is no class to map, it can be used to map just the XML.

다음은 POJO 클래스가 존재하지 않는 예제이다:

<class entity-name="Account" table="ACCOUNTS" node="account"> <id name="id" column="ACCOUNT_ID" node="@id" type="string"/> <many-to-one name="customerId" column="CUSTOMER_ID" node="customer/@id" embed-xml="false" entity-name="Customer"/> <property name="balance" column="BALANCE" node="balance" type="big_decimal"/> ... </class>

This mapping allows you to access the data as a dom4j tree, or as a graph of property name/value pairs or java Maps. The property names are purely logical constructs that can be referred to in HQL queries.

A range of Hibernate mapping elements accept the node attribute. This lets you specify the name of an XML attribute or element that holds the property or entity data. The format of the node attribute must be one of the following:

  • "element-name": map to the named XML element

  • "@attribute-name": map to the named XML attribute

  • ".": map to the parent element

  • "element-name/@attribute-name": map to the named attribute of the named element

For collections and single valued associations, there is an additional embed-xml attribute. If embed-xml="true", the default, the XML tree for the associated entity (or collection of value type) will be embedded directly in the XML tree for the entity that owns the association. Otherwise, if embed-xml="false", then only the referenced identifier value will appear in the XML for single point associations and collections will not appear at all.

Do not leave embed-xml="true" for too many associations, since XML does not deal well with circularity.

<class name="Customer" table="CUSTOMER" node="customer"> <id name="id" column="CUST_ID" node="@id"/> <map name="accounts" node="." embed-xml="true"> <key column="CUSTOMER_ID" not-null="true"/> <map-key column="SHORT_DESC" node="@short-desc" type="string"/> <one-to-many entity-name="Account" embed-xml="false" node="account"/> </map> <component name="name" node="name"> <property name="firstName" node="first-name"/> <property name="initial" node="initial"/> <property name="lastName" node="last-name"/> </component> ... </class>

In this case, the collection of account ids is embedded, but not the actual account data. The following HQL query:

from Customer c left join fetch c.accounts where c.lastName like :lastName

would return datasets such as this:

<customer id="123456789"> <account short-desc="Savings">987632567</account> <account short-desc="Credit Card">985612323</account> <name> <first-name>Gavin</first-name> <initial>A</initial> <last-name>King</last-name> </name> ... </customer>

만일 당신이 <one-to-many> 매핑에 대해 embed-xml="true"를 설정할 경우, 데이터는 다음과 같이 보일 수도 있다:

<customer id="123456789"> <account id="987632567" short-desc="Savings"> <customer id="123456789"/> <balance>100.29</balance> </account> <account id="985612323" short-desc="Credit Card"> <customer id="123456789"/> <balance>-2370.34</balance> </account> <name> <first-name>Gavin</first-name> <initial>A</initial> <last-name>King</last-name> </name> ... </customer>

Hibernate uses a fetching strategy to retrieve associated objects if the application needs to navigate the association. Fetch strategies can be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

Hibernate3는 다음 페칭 방도들을 정의한다:

  • Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

  • Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.

  • Subselect fetching: a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.

  • Batch fetching: an optimization strategy for select fetching. Hibernate retrieves a batch of entity instances or collections in a single SELECT by specifying a list of primary or foreign keys.

Hibernate는 또한 다음 사이를 구별 짓는다:

  • Immediate fetching: an association, collection or attribute is fetched immediately when the owner is loaded.

  • Lazy collection fetching: a collection is fetched when the application invokes an operation upon that collection. This is the default for collections.

  • "Extra-lazy" collection fetching: individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed. It is suitable for large collections.

  • Proxy fetching: a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.

  • "No-proxy" fetching: a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy; the association is fetched even when only the identifier is accessed. It is also more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.

  • Lazy attribute fetching: an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

We have two orthogonal notions here: when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.

By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

If you set hibernate.default_batch_fetch_size, Hibernate will use the batch fetch optimization for lazy fetching. This optimization can also be enabled at a more granular level.

Please be aware that access to a lazy association outside of the context of an open Hibernate session will result in an exception. For example:

s = sessions.openSession(); Transaction tx = s.beginTransaction(); User u = (User) s.createQuery("from User u where u.name=:userName") .setString("userName", userName).uniqueResult(); Map permissions = u.getPermissions(); tx.commit(); s.close(); Integer accessLevel = (Integer) permissions.get("accounts"); // Error!

Since the permissions collection was not initialized when the Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects. This can be fixed by moving the code that reads from the collection to just before the transaction is committed.

Alternatively, you can use a non-lazy collection or association, by specifying lazy="false" for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non-lazy associations in your object model, Hibernate will fetch the entire database into memory in every transaction.

On the other hand, you can use join fetching, which is non-lazy by nature, instead of select fetching in a particular transaction. We will now explain how to customize the fetching strategy. In Hibernate3, the mechanisms for choosing a fetch strategy are identical for single-valued associations and collections.

select 페칭(디폴트)은 N+1 selects 문제점들에 매우 취약해서, 우리는 매핑 문서에서 join 페칭을 사용 가능하게 하기를 원할 수도 있다:

<set name="permissions" fetch="join"> <key column="userId"/> <one-to-many class="Permission"/> </set
<many-to-one name="mother" class="Cat" fetch="join"/>

매핑 문서 내에 정의된 fetch 방도는 다음에 영향을 준다:

  • get() 또는 load()를 통한 검색

  • 연관이 네비게이트될 때 함축적으로 발생하는 검색

  • Criteria 질의들

  • subselect 페칭이 사용될 경우에 HQL 질의들

Irrespective of the fetching strategy you use, the defined non-lazy graph is guaranteed to be loaded into memory. This might, however, result in several immediate selects being used to execute a particular HQL query.

Usually, the mapping document is not used to customize fetching. Instead, we keep the default behavior, and override it for a particular transaction, using left join fetch in HQL. This tells Hibernate to fetch the association eagerly in the first select, using an outer join. In the Criteria query API, you would use setFetchMode(FetchMode.JOIN).

If you want to change the fetching strategy used by get() or load(), you can use a Criteria query. For example:

User user = (User) session.createCriteria(User.class) .setFetchMode("permissions", FetchMode.JOIN) .add( Restrictions.idEq(userId) ) .uniqueResult();

This is Hibernate's equivalent of what some ORM solutions call a "fetch plan".

A completely different approach to problems with N+1 selects is to use the second-level cache.

Lazy fetching for collections is implemented using Hibernate's own implementation of persistent collections. However, a different mechanism is needed for lazy behavior in single-ended associations. The target entity of the association must be proxied. Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement which is accessed via the CGLIB library.

At startup, Hibernate3 generates proxies by default for all persistent classes and uses them to enable lazy fetching of many-to-one and one-to-one associations.

The mapping file may declare an interface to use as the proxy interface for that class, with the proxy attribute. By default, Hibernate uses a subclass of the class. The proxied class must implement a default constructor with at least package visibility. This constructor is recommended for all persistent classes.

There are potential problems to note when extending this approach to polymorphic classes.For example:

<class name="Cat" proxy="Cat"> ...... <subclass name="DomesticCat"> ..... </subclass> </class>

첫 번째로, 심지어 기본 인스턴스가 DomesticCat의 인스턴스인 경우조차도, Cat의 인스턴스들은 결코 DomesticCat으로 타입캐스트가 가능하지 않을 것이다:

Cat cat = (Cat) session.load(Cat.class, id); // instantiate a proxy (does not hit the db) if ( cat.isDomesticCat() ) { // hit the db to initialize the proxy DomesticCat dc = (DomesticCat) cat; // Error! .... }

Secondly, it is possible to break proxy ==:

Cat cat = (Cat) session.load(Cat.class, id); // instantiate a Cat proxy DomesticCat dc = (DomesticCat) session.load(DomesticCat.class, id); // acquire new DomesticCat proxy! System.out.println(cat==dc); // false

하지만, 그 경우는 보이는 만큼 그렇게 나쁘지는 않다. 심지어 우리가 이제 다른 프락시 객체들에 대한 두 개의 참조를 가질지라도, 기본 인스턴스는 여전히 동일한 객체들일 것이다:

cat.setWeight(11.0); // hit the db to initialize the proxy System.out.println( dc.getWeight() ); // 11.0

Third, you cannot use a CGLIB proxy for a final class or a class with any final methods.

Finally, if your persistent object acquires any resources upon instantiation (e.g. in initializers or default constructor), then those resources will also be acquired by the proxy. The proxy class is an actual subclass of the persistent class.

These problems are all due to fundamental limitations in Java's single inheritance model. To avoid these problems your persistent classes must each implement an interface that declares its business methods. You should specify these interfaces in the mapping file where CatImpl implements the interface Cat and DomesticCatImpl implements the interface DomesticCat. For example:

<class name="CatImpl" proxy="Cat"> ...... <subclass name="DomesticCatImpl" proxy="DomesticCat"> ..... </subclass> </class>

Then proxies for instances of Cat and DomesticCat can be returned by load() or iterate().

Cat cat = (Cat) session.load(CatImpl.class, catid); Iterator iter = session.createQuery("from CatImpl as cat where cat.name='fritz'").iterate(); Cat fritz = (Cat) iter.next();

관계들은 또한 lazy 초기화 된다. 이것은 당신이 임의의 프로퍼티들을 CatImpl 타입이 아닌 Cat 타입으로 선언해야 함을 의미한다.

Certain operations do not require proxy initialization:

Hibernate는 equals() 또는 hashCode()를 오버라이드 시키는 영속 클래스들을 검출할 것이다.

By choosing lazy="no-proxy" instead of the default lazy="proxy", you can avoid problems associated with typecasting. However, buildtime bytecode instrumentation is required, and all operations will result in immediate proxy initialization.

LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state.

Sometimes a proxy or collection needs to be initialized before closing the Session. You can force initialization by calling cat.getSex() or cat.getKittens().size(), for example. However, this can be confusing to readers of the code and it is not convenient for generic code.

The static methods Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens.

Another option is to keep the Session open until all required collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:

  • In a web-based application, a servlet filter can be used to close the Session only at the end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the Session is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view. See the Hibernate Wiki for examples of this "Open Session in View" pattern.

  • In an application with a separate business tier, the business logic must "prepare" all collections that the web tier needs before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.

  • You can also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections or other proxies. Hibernate does not, and certainly should not, do this automatically since it would introduce impromptu transaction semantics.

Sometimes you do not want to initialize a large collection, but still need some information about it, like its size, for example, or a subset of the data.

당신은 그것을 초기화 시키지 않고서 콜렉션의 사이즈를 얻는데 콜렉션 필터를 사용할 수 있다:

( (Integer) s.createFilter( collection, "select count(*)" ).list().get(0) ).intValue()

createFilter() 메소드는 또한 전체 콜렉션을 초기화 시킬 필요 없이 콜렉션의 부분집합들을 효율적으로 검색하는데 사용된다:

s.createFilter( lazyCollection, "").setFirstResult(0).setMaxResults(10).list();

Using batch fetching, Hibernate can load several uninitialized proxies if one proxy is accessed. Batch fetching is an optimization of the lazy select fetching strategy. There are two ways you can configure batch fetching: on the class level and the collection level.

Batch fetching for classes/entities is easier to understand. Consider the following example: at runtime you have 25 Cat instances loaded in a Session, and each Cat has a reference to its owner, a Person. The Person class is mapped with a proxy, lazy="true". If you now iterate through all cats and call getOwner() on each, Hibernate will, by default, execute 25 SELECT statements to retrieve the proxied owners. You can tune this behavior by specifying a batch-size in the mapping of Person:

<class name="Person" batch-size="10">...</class>

Hibernate will now execute only three queries: the pattern is 10, 10, 5.

You can also enable batch fetching of collections. For example, if each Person has a lazy collection of Cats, and 10 persons are currently loaded in the Session, iterating through all persons will generate 10 SELECTs, one for every call to getCats(). If you enable batch fetching for the cats collection in the mapping of Person, Hibernate can pre-fetch collections:

<class name="Person"> <set name="cats" batch-size="3"> ... </set> </class>

batch-size 8로서, Hibernate는 4개의 SELECT들에서 3, 3, 3, 1 개의 콜렉션들을 로드시킬 것이다. 다시 그 속성의 값은 특정 Session 내에서 초기화 되지 않은 콜렉션들의 예상되는 개수에 의존한다.

Batch fetching of collections is particularly useful if you have a nested tree of items, i.e. the typical bill-of-materials pattern. However, a nested set or a materialized path might be a better option for read-mostly trees.

If one lazy collection or single-valued proxy has to be fetched, Hibernate will load all of them, re-running the original query in a subselect. This works in the same way as batch-fetching but without the piecemeal loading.

Hibernate3 supports the lazy fetching of individual properties. This optimization technique is also known as fetch groups. Please note that this is mostly a marketing feature; optimizing row reads is much more important than optimization of column reads. However, only loading some properties of a class could be useful in extreme cases. For example, when legacy tables have hundreds of columns and the data model cannot be improved.

lazy 프로퍼티 로딩을 이용가능하게 하려면, 당신의 특정 property 매핑들에 대해 lazy 속성을 설정하라:

<class name="Document"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="50"/> <property name="summary" not-null="true" length="200" lazy="true"/> <property name="text" not-null="true" length="2000" lazy="true"/> </class>

Lazy property loading requires buildtime bytecode instrumentation. If your persistent classes are not enhanced, Hibernate will ignore lazy property settings and return to immediate fetching.

bytecode 수단으로, 다음 Ant 태스크를 사용하라:

<target name="instrument" depends="compile"> <taskdef name="instrument" classname="org.hibernate.tool.instrument.InstrumentTask"> <classpath path="${jar.path}"/> <classpath path="${classes.dir}"/> <classpath refid="lib.class.path"/> </taskdef> <instrument verbose="true"> <fileset dir="${testclasses.dir}/org/hibernate/auction/model"> <include name="*.class"/> </fileset> </instrument> </target>

A different way of avoiding unnecessary column reads, at least for read-only transactions, is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution.

You can force the usual eager fetching of properties using fetch all properties in HQL.

A Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis. You can even plug in a clustered cache. Be aware that caches are not aware of changes made to the persistent store by another application. They can, however, be configured to regularly expire cached data.

You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate is bundled with a number of built-in integrations with the open-source cache providers that are listed below. You can also implement your own and plug it in as outlined above. Note that versions prior to 3.2 use EhCache as the default cache provider.


클래스 또는 콜렉션 매핑의 <cache> 요소는 다음 형식을 갖는다:

<cache 
    usage="transactional|read-write|nonstrict-read-write|read-only"  (1)
    region="RegionName"                                              (2)
    include="all|non-lazy"                                           (3)
/>
1

usage(필수) 캐싱 방도를 지정한다: transactionalread-writenonstrict-read-write 또는 read-only

2

region (optional: defaults to the class or collection role name): specifies the name of the second level cache region

3

include (optional: defaults to allnon-lazy: specifies that properties of the entity mapped with lazy="true" cannot be cached when attribute-level lazy fetching is enabled

Alternatively, you can specify <class-cache> and <collection-cache> elements in hibernate.cfg.xml.

usage 속성은 캐시 동시성 방도를 지정한다.

Whenever you pass an object to save()update() or saveOrUpdate(), and whenever you retrieve an object using load()get()list()iterate() or scroll(), that object is added to the internal cache of the Session.

When flush() is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur, or if you are processing a huge number of objects and need to manage memory efficiently, the evict() method can be used to remove the object and its collections from the first-level cache.

ScrollableResult cats = sess.createQuery("from Cat as cat").scroll(); //a huge result set while ( cats.next() ) { Cat cat = (Cat) cats.get(0); doSomethingWithACat(cat); sess.evict(cat); }

Session은 또한 인스턴스가 세션 캐시에 속하는지 여부를 결정하는데 contains() 메소드를 제공한다.

To evict all objects from the session cache, call Session.clear()

second-level 캐시의 경우, 하나의 인스턴스, 전체 클래스, 콜렉션 인스턴스 또는 전체 콜렉션 role의 캐시된 상태를 퇴거시키는 SessionFactory 상에 정의된 메소드들이 존재한다.

sessionFactory.evict(Cat.class, catId); //evict a particular Cat sessionFactory.evict(Cat.class); //evict all Cats sessionFactory.evictCollection("Cat.kittens", catId); //evict a particular collection of kittens sessionFactory.evictCollection("Cat.kittens"); //evict all kitten collections

The CacheMode controls how a particular session interacts with the second-level cache:

  • CacheMode.NORMAL: will read items from and write items to the second-level cache

  • CacheMode.GET: will read items from the second-level cache. Do not write to the second-level cache except when updating data

  • CacheMode.PUT: will write items to the second-level cache. Do not read from the second-level cache

  • CacheMode.REFRESH: will write items to the second-level cache. Do not read from the second-level cache. Bypass the effect of hibernate.cache.use_minimal_puts forcing a refresh of the second-level cache for all items read from the database

second-level 캐시 또는 질의 캐시 영역의 내용물을 브라우징하려면 Statistics API를 사용하라:

Map cacheEntries = sessionFactory.getStatistics() .getSecondLevelCacheStatistics(regionName) .getEntries();

You will need to enable statistics and, optionally, force Hibernate to keep the cache entries in a more readable format:

hibernate.generate_statistics true hibernate.cache.use_structured_entries true

Query result sets can also be cached. This is only useful for queries that are run frequently with the same parameters. You will first need to enable the query cache:

hibernate.cache.use_query_cache true

This setting creates two new cache regions: one holding cached query result sets (org.hibernate.cache.StandardQueryCache), the other holding timestamps of the most recent updates to queryable tables (org.hibernate.cache.UpdateTimestampsCache). Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. The query cache should always be used in conjunction with the second-level cache.

Most queries do not benefit from caching, so by default, queries are not cached. To enable caching, call Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed.

If you require fine-grained control over query cache expiration policies, you can specify a named cache region for a particular query by calling Query.setCacheRegion().

List blogs = sess.createQuery("from Blog blog where blog.blogger = :blogger") .setEntity("blogger", blogger) .setMaxResults(15) .setCacheable(true) .setCacheRegion("frontpages") .list();

만일 질의가 그것의 질의 캐시 영역의 갱신을 강제시켜야 하는 경우에, 당신은 Query.setCacheMode(CacheMode.REFRESH)를 호출해야 한다. 이것은 기본 데이터가 별도의 프로세스를 통해 업데이트되었고(예를 들면, Hibernate를 통해 변경되지 않았고) 특정 질의 결과 셋들을 선택적으로 갱신하는 것을 어플리케이션에게 허용해주는 경우들에서 특별히 유용하다. 이것은 SessionFactory.evictQueries()를 통해 질의 캐시 영역을 퇴거시키는 보다 효과적인 대안이다.

In the previous sections we have covered collections and their applications. In this section we explore some more issues in relation to collections at runtime.

Hibernate는 세 가지 기본적인 종류의 콜렉션들을 정의한다:

  • 값들을 가진 콜렉션들

  • one-to-many associations

  • many-to-many associations

이 분류는 여러 가지 테이블과 foreign key 관계들을 구별짓지만 우리가 관계형 모형에 대해 알 필요가 있는 모든 것을 우리에게 말해주지 않는다. 관계형 구조와 퍼포먼스 특징들을 완전하게 이해하기 위해, 우리는 또한 콜렉션 행들을 업데이트하거나 삭제하기 위해 Hibernate에 의해 사용되는 프라이머리 키의 구조를 검토해야 한다. 이것은 다음 분류를 제안한다:

  • 인덱싱 된 콜렉션들

  • set들

  • bag들

All indexed collections (maps, lists, and arrays) have a primary key consisting of the <key> and <index> columns. In this case, collection updates are extremely efficient. The primary key can be efficiently indexed and a particular row can be efficiently located when Hibernate tries to update or delete it.

Sets have a primary key consisting of <key> and element columns. This can be less efficient for some types of collection element, particularly composite elements or large text or binary fields, as the database may not be able to index a complex primary key as efficiently. However, for one-to-many or many-to-many associations, particularly in the case of synthetic identifiers, it is likely to be just as efficient. If you want SchemaExport to actually create the primary key of a <set>, you must declare all columns as not-null="true".

<idbag> mappings define a surrogate key, so they are efficient to update. In fact, they are the best case.

Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows. Hibernate resolves this problem by completely removing in a single DELETE and recreating the collection whenever it changes. This can be inefficient.

For a one-to-many association, the "primary key" may not be the physical primary key of the database table. Even in this case, the above classification is still useful. It reflects how Hibernate "locates" individual rows of the collection.

From the discussion above, it should be clear that indexed collections and sets allow the most efficient operation in terms of adding, removing and updating elements.

There is, arguably, one more advantage that indexed collections have over sets for many-to-many associations or collections of values. Because of the structure of a Set, Hibernate does not UPDATE a row when an element is "changed". Changes to a Set always work via INSERT and DELETE of individual rows. Once again, this consideration does not apply to one-to-many associations.

After observing that arrays cannot be lazy, you can conclude that lists, maps and idbags are the most performant (non-inverse) collection types, with sets not far behind. You can expect sets to be the most common kind of collection in Hibernate applications. This is because the "set" semantics are most natural in the relational model.

However, in well-designed Hibernate domain models, most collections are in fact one-to-many associations with inverse="true". For these associations, the update is handled by the many-to-one end of the association, and so considerations of collection update performance simply do not apply.

There is a particular case, however, in which bags, and also lists, are much more performant than sets. For a collection with inverse="true", the standard bidirectional one-to-many relationship idiom, for example, we can add elements to a bag or list without needing to initialize (fetch) the bag elements. This is because, unlike a setCollection.add() or Collection.addAll() must always return true for a bag or List. This can make the following common code much faster:

Parent p = (Parent) sess.load(Parent.class, id); Child c = new Child(); c.setParent(p); p.getChildren().add(c); //no need to fetch the collection! sess.flush();

Deleting collection elements one by one can sometimes be extremely inefficient. Hibernate knows not to do that in the case of an newly-empty collection (if you called list.clear(), for example). In this case, Hibernate will issue a single DELETE.

Suppose you added a single element to a collection of size twenty and then remove two elements. Hibernate will issue one INSERT statement and two DELETE statements, unless the collection is a bag. This is certainly desirable.

하지만, 우리가 두 개의 요소들을 남겨둔채 18 개의 요소들을 제거하고 나서 세 개의 새로운 요소들을 추가한다고 가정하자. 두 가지 가능한 처리 방법들이 존재한다.

  • 하나씩 열 여덟 개의 행들을 삭제한 다음에 세 개의 행들을 삽입시킨다

  • remove the whole collection in one SQL DELETE and insert all five current elements one by one

Hibernate cannot know that the second option is probably quicker. It would probably be undesirable for Hibernate to be that intuitive as such behavior might confuse database triggers, etc.

Fortunately, you can force this behavior (i.e. the second strategy) at any time by discarding (i.e. dereferencing) the original collection and returning a newly instantiated collection with all the current elements.

One-shot-delete does not apply to collections mapped inverse="true".

최적화는 퍼포먼스 관련 숫자들에 대한 모니터링과 접근 없이는 많이 사용되지 않는다. Hibernate는 그것의 내부적인 오퍼레이션들에 대한 전체 영역의 특징들을 제공한다. Hibernate에서 Statistics는 SessionFactory에 대해 이용 가능하다.

당신은 두 가지 방법들로 SessionFactory metrics에 접근할 수 있다. 당신의 첫 번째 옵션은 sessionFactory.getStatistics()를 호출하고 당신 스스로 Statistics를 읽거나 디스플레이 하는 것이다.

Hibernate can also use JMX to publish metrics if you enable the StatisticsService MBean. You can enable a single MBean for all your SessionFactory or one per factory. See the following code for minimalistic configuration examples:

// MBean service registration for a specific SessionFactory Hashtable tb = new Hashtable(); tb.put("type", "statistics"); tb.put("sessionFactory", "myFinancialApp"); ObjectName on = new ObjectName("hibernate", tb); // MBean object name StatisticsService stats = new StatisticsService(); // MBean implementation stats.setSessionFactory(sessionFactory); // Bind the stats to a SessionFactory server.registerMBean(stats, on); // Register the Mbean on the server
// MBean service registration for all SessionFactory's Hashtable tb = new Hashtable(); tb.put("type", "statistics"); tb.put("sessionFactory", "all"); ObjectName on = new ObjectName("hibernate", tb); // MBean object name StatisticsService stats = new StatisticsService(); // MBean implementation server.registerMBean(stats, on); // Register the MBean on the server

You can activate and deactivate the monitoring for a SessionFactory:

Statistics can be reset programmatically using the clear() method. A summary can be sent to a logger (info level) using the logSummary() method.

Hibernate provides a number of metrics, from basic information to more specialized information that is only relevant in certain scenarios. All available counters are described in the Statistics interface API, in three categories:

  • 열려진 세션들의 개수, 검색된 JDBC 커넥션들의 개수 등과 같은 일반적인 Session 사용에 관련된 metrics.

  • Metrics related to the entities, collections, queries, and caches as a whole (aka global metrics).

  • 특정한 엔티티, 콜렉션, 질의 또는 캐시 영역에 관련된 상세 metrics.

For example, you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Be aware that the number of milliseconds is subject to approximation in Java. Hibernate is tied to the JVM precision and on some platforms this might only be accurate to 10 seconds.

Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the StatisticsEntityStatisticsCollectionStatisticsSecondLevelCacheStatistics, and QueryStatistics API Javadoc for more information. The following code is a simple example:

Statistics stats = HibernateUtil.sessionFactory.getStatistics(); double queryCacheHitCount = stats.getQueryCacheHitCount(); double queryCacheMissCount = stats.getQueryCacheMissCount(); double queryCacheHitRatio = queryCacheHitCount / (queryCacheHitCount + queryCacheMissCount); log.info("Query Hit ratio:" + queryCacheHitRatio); EntityStatistics entityStats = stats.getEntityStatistics( Cat.class.getName() ); long changes = entityStats.getInsertCount() + entityStats.getUpdateCount() + entityStats.getDeleteCount(); log.info(Cat.class.getName() + " changed " + changes + "times" );

You can work on all entities, collections, queries and region caches, by retrieving the list of names of entities, collections, queries and region caches using the following methods: getQueries()getEntityNames()getCollectionRoleNames(), and getSecondLevelCacheRegionNames().

Roundtrip engineering with Hibernate is possible using a set of Eclipse plugins, commandline tools, and Ant tasks.

Hibernate Tools currently include plugins for the Eclipse IDE as well as Ant tasks for reverse engineering of existing databases:

  • Mapping Editor: an editor for Hibernate XML mapping files that supports auto-completion and syntax highlighting. It also supports semantic auto-completion for class names and property/field names, making it more versatile than a normal XML editor.

  • Console: the console is a new view in Eclipse. In addition to a tree overview of your console configurations, you are also provided with an interactive view of your persistent classes and their relationships. The console allows you to execute HQL queries against your database and browse the result directly in Eclipse.

  • Development Wizards: several wizards are provided with the Hibernate Eclipse tools. You can use a wizard to quickly generate Hibernate configuration (cfg.xml) files, or to reverse engineer an existing database schema into POJO source files and Hibernate mapping files. The reverse engineering wizard supports customizable templates.

Please refer to the Hibernate Tools package documentation for more information.

However, the Hibernate main package comes bundled with an integrated tool : SchemaExport aka hbm2ddl.It can even be used from "inside" Hibernate.

DDL can be generated from your mapping files by a Hibernate utility. The generated schema includes referential integrity constraints, primary and foreign keys, for entity and collection tables. Tables and sequences are also created for mapped identifier generators.

You must specify a SQL Dialect via the hibernate.dialect property when using this tool, as DDL is highly vendor-specific.

First, you must customize your mapping files to improve the generated schema. The next section covers schema customization.

Many Hibernate mapping elements define optional attributes named lengthprecision and scale. You can set the length, precision and scale of a column with this attribute.

<property name="zip" length="5"/>
<property name="balance" precision="12" scale="2"/>

Some tags also accept a not-null attribute for generating a NOT NULL constraint on table columns, and a unique attribute for generating UNIQUE constraint on table columns.

<many-to-one name="bar" column="barId" not-null="true"/>
<element column="serialNumber" type="long" not-null="true" unique="true"/>

unique-key attribute can be used to group columns in a single, unique key constraint. Currently, the specified value of the unique-key attribute is not used to name the constraint in the generated DDL. It is only used to group the columns in the mapping file.

<many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/> <property name="employeeId" unique-key="OrgEmployee"/>

An index attribute specifies the name of an index that will be created using the mapped column or columns. Multiple columns can be grouped into the same index by simply specifying the same index name.

<property name="lastName" index="CustName"/> <property name="firstName" index="CustName"/>

foreign-key attribute can be used to override the name of any generated foreign key constraint.

<many-to-one name="bar" column="barId" foreign-key="FKFooBar"/>

많은 매핑 요소들은 또한 하나의 자식 <column> 요소를 허용한다. 이것은 특히 다중 컬럼 타입들을 매핑하는데 유용하다:

<property name="name" type="my.customtypes.Name"/> <column name="last" not-null="true" index="bar_idx" length="30"/> <column name="first" not-null="true" index="bar_idx" length="20"/> <column name="initial"/> </property>

The default attribute allows you to specify a default value for a column.You should assign the same value to the mapped property before saving a new instance of the mapped class.

<property name="credits" type="integer" insert="false"> <column name="credits" default="10"/> </property>
<version name="version" type="integer" insert="false"> <column name="version" default="0"/> </property>

sql-type 속성은 SQL 데이터타입에 대한 Hibernate 타입의 디폴트 매핑을 오버라이드 시키는 것을 사용자에게 허용해준다.

<property name="balance" type="float"> <column name="balance" sql-type="decimal(13,3)"/> </property>

check 속성은 check 컨스트레인트를 지정하는 것을 당신에게 허용해준다.

<property name="foo" type="integer"> <column name="foo" check="foo > 10"/> </property>
<class name="Foo" table="foos" check="bar < 100.0"> ... <property name="bar" type="float"/> </class>

The following table summarizes these optional attributes.


<comment> 요소는 생성된 스키마에 대한 주석들을 지정하는 것을 당신에게 허용해준다.

<class name="Customer" table="CurCust">
    <comment>Current customers only</comment>
    ...
</class>
<property name="balance">
    <column name="bal">
        <comment>Balance in USD</comment>
    </column>
</property>

This results in a comment on table or comment on column statement in the generated DDL where supported.

Database properties can be specified:

  • -D<property>를 가진 시스템 프로퍼티로서

  • hibernate.properties 내에서

  • --properties를 가진 명명된 프로퍼티들 내에서

필요한 프로퍼티들은 다음과 같다:


The SchemaValidator tool will validate that the existing database schema "matches" your mapping documents. The SchemaValidator depends heavily upon the JDBC metadata API and, as such, will not work with all JDBC drivers. This tool is extremely useful for testing.

java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaValidator options mapping_files


You can embed SchemaValidator in your application:

Configuration cfg = ....;
new SchemaValidator(cfg).validate();

One of the first things that new users want to do with Hibernate is to model a parent/child type relationship. There are two different approaches to this. The most convenient approach, especially for new users, is to model both Parent and Child as entity classes with a <one-to-many> association from Parent to Child. The alternative approach is to declare the Child as a <composite-element>. The default semantics of a one-to-many association in Hibernate are much less close to the usual semantics of a parent/child relationship than those of a composite element mapping. We will explain how to use a bidirectional one-to-many association with cascades to model a parent/child relationship efficiently and elegantly.

Hibernate collections are considered to be a logical part of their owning entity and not of the contained entities. Be aware that this is a critical distinction that has the following consequences:

  • When you remove/add an object from/to a collection, the version number of the collection owner is incremented.

  • If an object that was removed from a collection is an instance of a value type (e.g. a composite element), that object will cease to be persistent and its state will be completely removed from the database. Likewise, adding a value type instance to the collection will cause its state to be immediately persistent.

  • Conversely, if an entity is removed from a collection (a one-to-many or many-to-many association), it will not be deleted by default. This behavior is completely consistent; a change to the internal state of another entity should not cause the associated entity to vanish. Likewise, adding an entity to a collection does not cause that entity to become persistent, by default.

Adding an entity to a collection, by default, merely creates a link between the two entities. Removing the entity will remove the link. This is appropriate for all sorts of cases. However, it is not appropriate in the case of a parent/child relationship. In this case, the life of the child is bound to the life cycle of the parent.

Parent로부터 Child로의 간단한 <one-to-many> 연관관계로 시작한다고 가정하자.

<set name="children"> <key column="parent_id"/> <one-to-many class="Child"/> </set>

If we were to execute the following code:

Parent p = .....; Child c = new Child(); p.getChildren().add(c); session.save(c); session.flush();

Hibernate는 두 개의 SQL 문장들을 실행할 것이다:

This is not only inefficient, but also violates any NOT NULL constraint on the parent_id column. You can fix the nullability constraint violation by specifying not-null="true" in the collection mapping:

<set name="children"> <key column="parent_id" not-null="true"/> <one-to-many class="Child"/> </set>

하지만 이것은 권장되는 해결책이 아니다.

The underlying cause of this behavior is that the link (the foreign key parent_id) from p to c is not considered part of the state of the Child object and is therefore not created in the INSERT. The solution is to make the link part of the Child mapping.

<many-to-one name="parent" column="parent_id" not-null="true"/>

You also need to add the parent property to the Child class.

Now that the Child entity is managing the state of the link, we tell the collection not to update the link. We use the inverse attribute to do this:

<set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set>

The following code would be used to add a new Child:

Parent p = (Parent) session.load(Parent.class, pid); Child c = new Child(); c.setParent(p); p.getChildren().add(c); session.save(c); session.flush();

Only one SQL INSERT would now be issued.

You could also create an addChild() method of Parent.

public void addChild(Child c) { c.setParent(this); children.add(c); }

The code to add a Child looks like this:

Parent p = (Parent) session.load(Parent.class, pid); Child c = new Child(); p.addChild(c); session.save(c); session.flush();

You can address the frustrations of the explicit call to save() by using cascades.

<set name="children" inverse="true" cascade="all"> <key column="parent_id"/> <one-to-many class="Child"/> </set>

This simplifies the code above to:

Parent p = (Parent) session.load(Parent.class, pid); Child c = new Child(); p.addChild(c); session.flush();

Similarly, we do not need to iterate over the children when saving or deleting a Parent. The following removes p and all its children from the database.

Parent p = (Parent) session.load(Parent.class, pid); session.delete(p); session.flush();

However, the following code:

Parent p = (Parent) session.load(Parent.class, pid); Child c = (Child) p.getChildren().iterator().next(); p.getChildren().remove(c); c.setParent(null); session.flush();

will not remove c from the database. In this case, it will only remove the link to p and cause a NOT NULL constraint violation. You need to explicitly delete() the Child.

Parent p = (Parent) session.load(Parent.class, pid); Child c = (Child) p.getChildren().iterator().next(); p.getChildren().remove(c); session.delete(c); session.flush();

In our case, a Child cannot exist without its parent. So if we remove a Child from the collection, we do want it to be deleted. To do this, we must use cascade="all-delete-orphan".

<set name="children" inverse="true" cascade="all-delete-orphan"> <key column="parent_id"/> <one-to-many class="Child"/> </set>

Even though the collection mapping specifies inverse="true", cascades are still processed by iterating the collection elements. If you need an object be saved, deleted or updated by cascade, you must add it to the collection. It is not enough to simply call setParent().

Suppose we loaded up a Parent in one Session, made some changes in a UI action and wanted to persist these changes in a new session by calling update(). The Parent will contain a collection of children and, since the cascading update is enabled, Hibernate needs to know which children are newly instantiated and which represent existing rows in the database. We will also assume that both Parent and Child have generated identifier properties of type Long. Hibernate will use the identifier and version/timestamp property value to determine which of the children are new. (See 10.7절. “자동적인 상태 검출”.) In Hibernate3, it is no longer necessary to specify an unsaved-value explicitly.

The following code will update parent and child and insert newChild:

//parent and child were both loaded in a previous session parent.addChild(child); Child newChild = new Child(); parent.addChild(newChild); session.update(parent); session.flush();

This may be suitable for the case of a generated identifier, but what about assigned identifiers and composite identifiers? This is more difficult, since Hibernate cannot use the identifier property to distinguish between a newly instantiated object, with an identifier assigned by the user, and an object loaded in a previous session. In this case, Hibernate will either use the timestamp or version property, or will actually query the second-level cache or, worst case, the database, to see if the row exists.

The sections we have just covered can be a bit confusing. However, in practice, it all works out nicely. Most Hibernate applications use the parent/child pattern in many places.

We mentioned an alternative in the first paragraph. None of the above issues exist in the case of <composite-element> mappings, which have exactly the semantics of a parent/child relationship. Unfortunately, there are two big limitations with composite element classes: composite elements cannot own collections and they should not be the child of any entity other than the unique parent.

The following class demonstrates some of the kinds of things we can do with these classes using Hibernate:

package eg; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class BlogMain { private SessionFactory _sessions; public void configure() throws HibernateException { _sessions = new Configuration() .addClass(Blog.class) .addClass(BlogItem.class) .buildSessionFactory(); } public void exportTables() throws HibernateException { Configuration cfg = new Configuration() .addClass(Blog.class) .addClass(BlogItem.class); new SchemaExport(cfg).create(true, true); } public Blog createBlog(String name) throws HibernateException { Blog blog = new Blog(); blog.setName(name); blog.setItems( new ArrayList() ); Session session = _sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.persist(blog); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return blog; } public BlogItem createBlogItem(Blog blog, String title, String text) throws HibernateException { BlogItem item = new BlogItem(); item.setTitle(title); item.setText(text); item.setBlog(blog); item.setDatetime( Calendar.getInstance() ); blog.getItems().add(item); Session session = _sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(blog); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return item; } public BlogItem createBlogItem(Long blogid, String title, String text) throws HibernateException { BlogItem item = new BlogItem(); item.setTitle(title); item.setText(text); item.setDatetime( Calendar.getInstance() ); Session session = _sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Blog blog = (Blog) session.load(Blog.class, blogid); item.setBlog(blog); blog.getItems().add(item); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return item; } public void updateBlogItem(BlogItem item, String text) throws HibernateException { item.setText(text); Session session = _sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(item); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } } public void updateBlogItem(Long itemid, String text) throws HibernateException { Session session = _sessions.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); BlogItem item = (BlogItem) session.load(BlogItem.class, itemid); item.setText(text); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } } public List listAllBlogNamesAndItemCounts(int max) throws HibernateException { Session session = _sessions.openSession(); Transaction tx = null; List result = null; try { tx = session.beginTransaction(); Query q = session.createQuery( "select blog.id, blog.name, count(blogItem) " + "from Blog as blog " + "left outer join blog.items as blogItem " + "group by blog.name, blog.id " + "order by max(blogItem.datetime)" ); q.setMaxResults(max); result = q.list(); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return result; } public Blog getBlogAndAllItems(Long blogid) throws HibernateException { Session session = _sessions.openSession(); Transaction tx = null; Blog blog = null; try { tx = session.beginTransaction(); Query q = session.createQuery( "from Blog as blog " + "left outer join fetch blog.items " + "where blog.id = :blogid" ); q.setParameter("blogid", blogid); blog = (Blog) q.uniqueResult(); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return blog; } public List listBlogsAndRecentItems() throws HibernateException { Session session = _sessions.openSession(); Transaction tx = null; List result = null; try { tx = session.beginTransaction(); Query q = session.createQuery( "from Blog as blog " + "inner join blog.items as blogItem " + "where blogItem.datetime > :minDate" ); Calendar cal = Calendar.getInstance(); cal.roll(Calendar.MONTH, false); q.setCalendar("minDate", cal); result = q.list(); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { session.close(); } return result; } }

This chapters explores some more complex association mappings.

The following model of the relationship between Employer and Employee uses an entity class (Employment) to represent the association. You can do this when there might be more than one period of employment for the same two parties. Components are used to model monetary values and employee names.

Here is a possible mapping document:

<hibernate-mapping> <class name="Employer" table="employers"> <id name="id"> <generator class="sequence"> <param name="sequence">employer_id_seq</param> </generator> </id> <property name="name"/> </class> <class name="Employment" table="employment_periods"> <id name="id"> <generator class="sequence"> <param name="sequence">employment_id_seq</param> </generator> </id> <property name="startDate" column="start_date"/> <property name="endDate" column="end_date"/> <component name="hourlyRate" class="MonetaryAmount"> <property name="amount"> <column name="hourly_rate" sql-type="NUMERIC(12, 2)"/> </property> <property name="currency" length="12"/> </component> <many-to-one name="employer" column="employer_id" not-null="true"/> <many-to-one name="employee" column="employee_id" not-null="true"/> </class> <class name="Employee" table="employees"> <id name="id"> <generator class="sequence"> <param name="sequence">employee_id_seq</param> </generator> </id> <property name="taxfileNumber"/> <component name="name" class="Name"> <property name="firstName"/> <property name="initial"/> <property name="lastName"/> </component> </class> </hibernate-mapping>

Here is the table schema generated by SchemaExport.

create table employers ( id BIGINT not null, name VARCHAR(255), primary key (id) ) create table employment_periods ( id BIGINT not null, hourly_rate NUMERIC(12, 2), currency VARCHAR(12), employee_id BIGINT not null, employer_id BIGINT not null, end_date TIMESTAMP, start_date TIMESTAMP, primary key (id) ) create table employees ( id BIGINT not null, firstName VARCHAR(255), initial CHAR(1), lastName VARCHAR(255), taxfileNumber VARCHAR(255), primary key (id) ) alter table employment_periods add constraint employment_periodsFK0 foreign key (employer_id) references employers alter table employment_periods add constraint employment_periodsFK1 foreign key (employee_id) references employees create sequence employee_id_seq create sequence employment_id_seq create sequence employer_id_seq

Consider the following model of the relationships between WorkAuthor and Person. In the example, the relationship between Work and Author is represented as a many-to-many association and the relationship between Author and Person is represented as one-to-one association. Another possibility would be to have Author extend Person.

다음 매핑 문서는 이들 관계들을 정확하게 표현한다:

<hibernate-mapping> <class name="Work" table="works" discriminator-value="W"> <id name="id" column="id"> <generator class="native"/> </id> <discriminator column="type" type="character"/> <property name="title"/> <set name="authors" table="author_work"> <key column name="work_id"/> <many-to-many class="Author" column name="author_id"/> </set> <subclass name="Book" discriminator-value="B"> <property name="text"/> </subclass> <subclass name="Song" discriminator-value="S"> <property name="tempo"/> <property name="genre"/> </subclass> </class> <class name="Author" table="authors"> <id name="id" column="id"> <!-- The Author must have the same identifier as the Person --> <generator class="assigned"/> </id> <property name="alias"/> <one-to-one name="person" constrained="true"/> <set name="works" table="author_work" inverse="true"> <key column="author_id"/> <many-to-many class="Work" column="work_id"/> </set> </class> <class name="Person" table="persons"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name"/> </class> </hibernate-mapping>

There are four tables in this mapping: worksauthors and persons hold work, author and person data respectively. author_work is an association table linking authors to works. Here is the table schema, as generated by SchemaExport:

create table works ( id BIGINT not null generated by default as identity, tempo FLOAT, genre VARCHAR(255), text INTEGER, title VARCHAR(255), type CHAR(1) not null, primary key (id) ) create table author_work ( author_id BIGINT not null, work_id BIGINT not null, primary key (work_id, author_id) ) create table authors ( id BIGINT not null generated by default as identity, alias VARCHAR(255), primary key (id) ) create table persons ( id BIGINT not null generated by default as identity, name VARCHAR(255), primary key (id) ) alter table authors add constraint authorsFK0 foreign key (id) references persons alter table author_work add constraint author_workFK0 foreign key (author_id) references authors alter table author_work add constraint author_workFK1 foreign key (work_id) references works

In this section we consider a model of the relationships between CustomerOrderLine Item and Product. There is a one-to-many association between Customer and Order, but how can you represent Order / LineItem / Product? In the example, LineItem is mapped as an association class representing the many-to-many association between Order and Product. In Hibernate this is called a composite element.

The mapping document will look like this:

<hibernate-mapping> <class name="Customer" table="customers"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="orders" inverse="true"> <key column="customer_id"/> <one-to-many class="Order"/> </set> </class> <class name="Order" table="orders"> <id name="id"> <generator class="native"/> </id> <property name="date"/> <many-to-one name="customer" column="customer_id"/> <list name="lineItems" table="line_items"> <key column="order_id"/> <list-index column="line_number"/> <composite-element class="LineItem"> <property name="quantity"/> <many-to-one name="product" column="product_id"/> </composite-element> </list> </class> <class name="Product" table="products"> <id name="id"> <generator class="native"/> </id> <property name="serialNumber"/> </class> </hibernate-mapping>

customersordersline_items 그리고 products는 각각 고객 데이터, 주문 데이터, 주문 라인 아이템 데이터, 그리고 제품 데이터를 보관한다. line_items는 또한 주문들을 제품들과 연결시키는 연관 테이블로서 동작한다.

create table customers ( id BIGINT not null generated by default as identity, name VARCHAR(255), primary key (id) ) create table orders ( id BIGINT not null generated by default as identity, customer_id BIGINT, date TIMESTAMP, primary key (id) ) create table line_items ( line_number INTEGER not null, order_id BIGINT not null, product_id BIGINT, quantity INTEGER, primary key (order_id, line_number) ) create table products ( id BIGINT not null generated by default as identity, serialNumber VARCHAR(255), primary key (id) ) alter table orders add constraint ordersFK0 foreign key (customer_id) references customers alter table line_items add constraint line_itemsFK0 foreign key (product_id) references products alter table line_items add constraint line_itemsFK1 foreign key (order_id) references orders

These examples are available from the Hibernate test suite. You will find many other useful example mappings there by searching in the test folder of the Hibernate distribution.

<class name="Customer"> <id name="customerId" length="10"> <generator class="assigned"/> </id> <property name="name" not-null="true" length="100"/> <property name="address" not-null="true" length="200"/> <list name="orders" inverse="true" cascade="save-update"> <key column="customerId"/> <index column="orderNumber"/> <one-to-many class="Order"/> </list> </class> <class name="Order" table="CustomerOrder" lazy="true"> <synchronize table="LineItem"/> <synchronize table="Product"/> <composite-id name="id" class="Order$Id"> <key-property name="customerId" length="10"/> <key-property name="orderNumber"/> </composite-id> <property name="orderDate" type="calendar_date" not-null="true"/> <property name="total"> <formula> ( select sum(li.quantity*p.price) from LineItem li, Product p where li.productId = p.productId and li.customerId = customerId and li.orderNumber = orderNumber ) </formula> </property> <many-to-one name="customer" column="customerId" insert="false" update="false" not-null="true"/> <bag name="lineItems" fetch="join" inverse="true" cascade="save-update"> <key> <column name="customerId"/> <column name="orderNumber"/> </key> <one-to-many class="LineItem"/> </bag> </class> <class name="LineItem"> <composite-id name="id" class="LineItem$Id"> <key-property name="customerId" length="10"/> <key-property name="orderNumber"/> <key-property name="productId" length="10"/> </composite-id> <property name="quantity"/> <many-to-one name="order" insert="false" update="false" not-null="true"> <column name="customerId"/> <column name="orderNumber"/> </many-to-one> <many-to-one name="product" insert="false" update="false" not-null="true" column="productId"/> </class> <class name="Product"> <synchronize table="LineItem"/> <id name="productId" length="10"> <generator class="assigned"/> </id> <property name="description" not-null="true" length="200"/> <property name="price" length="3"/> <property name="numberAvailable"/> <property name="numberOrdered"> <formula> ( select sum(li.quantity) from LineItem li where li.productId = productId ) </formula> </property> </class>
Write fine-grained classes and map them using <component>:

streetsuburbstatepostcode를 캡슐화 시키는데 Address 클래스를 사용하라. 이것은 코드 재사용성을 촉진시키고 리팩토링을 단순화 시킨다.

Declare identifier properties on persistent classes:

Hibernate makes identifier properties optional. There are a range of reasons why you should use them. We recommend that identifiers be 'synthetic', that is, generated with no business meaning.

Identify natural keys:

모든 엔티티들에 대해 고유 키들을 식별하고, <natural-id>를 사용하여 그것들을 매핑하라. 고유 키를 구성하는 프로퍼티들을 비교하기 위해 equals()와 hashCode()를 구현하라.

Place each class mapping in its own file:

Do not use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes sense, particularly in a team environment.

Load mappings as resources:

그것들이 매핑하는 클래스들에 따라서 매핑들을 배치하라

Consider externalizing query strings:

This is recommended if your queries call non-ANSI-standard SQL functions. Externalizing the query strings to mapping files will make the application more portable.

바인드 변수들을 사용하라.

As in JDBC, always replace non-constant values by "?". Do not use string manipulation to bind a non-constant value in a query. You should also consider using named parameters in queries.

Do not manage your own JDBC connections:

Hibernate allows the application to manage JDBC connections, but his approach should be considered a last-resort. If you cannot use the built-in connection providers, consider providing your own implementation of org.hibernate.connection.ConnectionProvider.

Consider using a custom type:

Suppose you have a Java type from a library that needs to be persisted but does not provide the accessors needed to map it as a component. You should consider implementing org.hibernate.UserType. This approach frees the application code from implementing transformations to/from a Hibernate type.

Use hand-coded JDBC in bottlenecks:

In performance-critical areas of the system, some kinds of operations might benefit from direct JDBC. Do not assume, however, that JDBC is necessarily faster. Please wait until you know something is a bottleneck. If you need to use direct JDBC, you can open a Hibernate Session and usingfile:///usr/share/doc/HTML/en-US/index.html that JDBC connection. This way you can still use the same transaction strategy and underlying connection provider.

Understand Session flushing:

Sometimes the Session synchronizes its persistent state with the database. Performance will be affected if this process occurs too often. You can sometimes minimize unnecessary flushing by disabling automatic flushing, or even by changing the order of queries and other operations within a particular transaction.

In a three tiered architecture, consider using detached objects:

When using a servlet/session bean architecture, you can pass persistent objects loaded in the session bean to and from the servlet/JSP layer. Use a new session to service each request. Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.

In a two tiered architecture, consider using long persistence contexts:

Database Transactions have to be as short as possible for best scalability. However, it is often necessary to implement long running application transactions, a single unit-of-work from the point of view of a user. An application transaction might span several client request/response cycles. It is common to use detached objects to implement application transactions. An appropriate alternative in a two tiered architecture, is to maintain a single open persistence contact session for the whole life cycle of the application transaction. Then simply disconnect from the JDBC connection at the end of each request and reconnect at the beginning of the subsequent request. Never share a single session across more than one application transaction or you will be working with stale data.

Do not treat exceptions as recoverable:

This is more of a necessary practice than a "best" practice. When an exception occurs, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state. For example, do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.

Prefer lazy fetching for associations:

Use eager fetching sparingly. Use proxies and lazy collections for most associations to classes that are not likely to be completely held in the second-level cache. For associations to cached classes, where there is an a extremely high probability of a cache hit, explicitly disable eager fetching using lazy="false". When join fetching is appropriate to a particular use case, use a query with a left join fetch.

Use the open session in view pattern, or a disciplined assembly phase to avoid problems with unfetched data:

Hibernate frees the developer from writing tedious Data Transfer Objects (DTO). In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier. Hibernate eliminates the first purpose. Unless you are prepared to hold the persistence context (the session) open across the view rendering process, you will still need an assembly phase. Think of your business methods as having a strict contract with the presentation tier about what data is available in the detached objects. This is not a limitation of Hibernate. It is a fundamental requirement of safe transactional data access.

Consider abstracting your business logic from Hibernate:

Hide Hibernate data-access code behind an interface. Combine the DAO and Thread Local Session patterns. You can even have some classes persisted by handcoded JDBC associated to Hibernate via a UserType. This advice is, however, intended for "sufficiently large" applications. It is not appropriate for an application with five tables.

Do not use exotic association mappings:

Practical test cases for real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, most associations are one-to-many and many-to-one. For this reason, you should proceed cautiously when using any other association style.

Prefer bidirectional associations:

단방향 연관들은 질의하기가 더 어렵다. 많은 어플리케이션에서, 거의 모든 연관들은 질의들 내에서 양 방향으로 네비게이트 가능해야 한다.

One of the selling points of Hibernate (and really Object/Relational Mapping as a whole) is the notion of database portability. This could mean an internal IT user migrating from one database vendor to another, or it could mean a framework or deployable application consuming Hibernate to simultaneously target multiple database products by their users. Regardless of the exact scenario, the basic idea is that you want Hibernate to help you run against any number of databases without changes to your code, and ideally without any changes to the mapping metadata.

The first line of portability for Hibernate is the dialect, which is a specialization of the org.hibernate.dialect.Dialect contract. A dialect encapsulates all the differences in how Hibernate must communicate with a particular database to accomplish some task like getting a sequence value or structuring a SELECT query. Hibernate bundles a wide range of dialects for many of the most popular databases. If you find that your particular database is not among them, it is not terribly difficult to write your own.

Originally, Hibernate would always require that users specify which dialect to use. In the case of users looking to simultaneously target multiple databases with their build that was problematic. Generally this required their users to configure the Hibernate dialect or defining their own method of setting that value.

Starting with version 3.2, Hibernate introduced the notion of automatically detecting the dialect to use based on the java.sql.DatabaseMetaData obtained from a java.sql.Connection to that database. This was much better, expect that this resolution was limited to databases Hibernate know about ahead of time and was in no way configurable or overrideable.

Starting with version 3.3, Hibernate has a fare more powerful way to automatically determine which dialect to should be used by relying on a series of delegates which implement the org.hibernate.dialect.resolver.DialectResolver which defines only a single method:

public Dialect resolveDialect(DatabaseMetaData metaData) throws JDBCConnectionException

. The basic contract here is that if the resolver 'understands' the given database metadata then it returns the corresponding Dialect; if not it returns null and the process continues to the next resolver. The signature also identifies org.hibernate.exception.JDBCConnectionException as possibly being thrown. A JDBCConnectionException here is interpreted to imply a "non transient" (aka non-recoverable) connection problem and is used to indicate an immediate stop to resolution attempts. All other exceptions result in a warning and continuing on to the next resolver.

The cool part about these resolvers is that users can also register their own custom resolvers which will be processed ahead of the built-in Hibernate ones. This might be useful in a number of different situations: it allows easy integration for auto-detection of dialects beyond those shipped with HIbernate itself; it allows you to specify to use a custom dialect when a particular database is recognized; etc. To register one or more resolvers, simply specify them (seperated by commas, tabs or spaces) using the 'hibernate.dialect_resolvers' configuration setting (see the DIALECT_RESOLVERS constant on org.hibernate.cfg.Environment).

When considering portability between databases, another important decision is selecting the identifier generation stratagy you want to use. Originally Hibernate provided the native generator for this purpose, which was intended to select between a sequenceidentity, or table strategy depending on the capability of the underlying database. However, an insidious implication of this approach comes about when targtetting some databases which support identity generation and some which do not. identity generation relies on the SQL definition of an IDENTITY (or auto-increment) column to manage the identifier value; it is what is known as a post-insert generation strategy becauase the insert must actually happen before we can know the identifier value. Because Hibernate relies on this identifier value to uniquely reference entities within a persistence context it must then issue the insert immediately when the users requests the entitiy be associated with the session (like via save() e.g.) regardless of current transactional semantics.

The underlying issue is that the actual semanctics of the application itself changes in these cases.

Starting with version 3.2.3, Hibernate comes with a set of enhanced identifier generators targetting portability in a much different way.

참고

There are specifically 2 bundled enhancedgenerators:

  • org.hibernate.id.enhanced.SequenceStyleGenerator

  • org.hibernate.id.enhanced.TableGenerator

The idea behind these generators is to port the actual semantics of the identifer value generation to the different databases. For example, the org.hibernate.id.enhanced.SequenceStyleGenerator mimics the behavior of a sequence on databases which do not support sequences by using a table.

This section scheduled for completion at a later date...

[PoEAA] Patterns of Enterprise Application Architecture0-321-12742-0. 지은이 Martin Fowler. 저작권 © 2003 Pearson Education, Inc.. Addison-Wesley Publishing Company.

[JPwHJava Persistence with HibernateSecond Edition of Hibernate in Action. 1-932394-88-5. http://www.manning.com/bauer2 . 지은이 Christian Bauer 그리고 Gavin King저작권 © 2007 Manning Publications Co.. Manning Publications Co..


Posted by 1010
98..Etc/Hibernate2012. 4. 10. 10:09
반응형

증상

org.springframework.transaction.CannotCreateTransactionException: Could not create Hibernate transaction; nested exception is net.sf.hibernate.exception.GenericJDBCException: Cannot open connection
net.sf.hibernate.exception.GenericJDBCException: Cannot open connection
at net.sf.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:80)
at net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69)
at net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
....
....
Caused by: java.sql.SQLException: An SQLException was provoked by the following failure: com.mchange.v2.resourcepool.ResourcePoolException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:68)
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:57)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:213)
at com.mchange.v2.c3p0.PoolBackedDataSource.getConnection(PoolBackedDataSource.java:64)
at net.sf.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:33)
at net.sf.hibernate.impl.BatcherImpl.openConnection(BatcherImpl.java:292)
... 63 more
Caused by: com.mchange.v2.resourcepool.ResourcePoolException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAcquire(BasicResourcePool.java:870)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:201)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:209)
... 66 more

원인

This error is stating that it cannot get a connection to the database.

Possibly causes are:
1) The database is down, possibly due to being overwhelmed.
2) The server confluence is on, cannot reach the server the database is on

3) Your username and password that you used for your database in confluence_home/confluence.cfg.xml is incorrect

4) There are not enough JDBC connections available during the upgrade process

해결 방법

1) Check with your DBA that your database is up and running. If the problem has happened after a period of Confluence usage, check to make sure the database indices are installed correctly. See Improving Database Performance for details.
2) Talk to your network administrator to find out why your confluence server cannot establish a connection to the database
3) Check with your DBA that your user/pass that you are using for your database is correct and hasn't been changed

4) Go to the confluence.cfg.xml file in the Confluence Home Directory. There is an entry in this file that will look like this:

<property name="hibernate.c3p0.max_size">30</property>

Set the max_size connections to a greater number then is set in the file currently. This particular problem was encountered during an upgrade. Please refer to this knowledge base article:

Confluence Slows and Times out During Periods of High Load due to DB Connection Pool

Posted by 1010
05.JSP2012. 4. 9. 11:35
반응형

ScriptX printing: technical manual

January 2011 (Version 6.6 and later)


Contents

Overview
Introduction
Summary of examples
Advanced Control of HTML Printing with ScriptX
Technical support
How do I use ScriptX?
Client-side (within Internet Explorer)
Basic functionality: smsx.cab
Advanced functionality: smsx.cab
How to check whether or not the object is properly installed
Testing your print-outs
Server-side deployment
Within a desktop application
Reference

Overview

Introduction

MeadCo's ScriptX is a suite of ActiveX technology components designed to provide absolute control over document printing operations from client and server computers running the Microsoft Windows Web Browsing Platform.

Part of its purpose is to ensure the consistent formatting and appearance of printed output from any local or networked printer, regardless of the printing attributes already set in that computer's Internet Explorer (IE) browser. ScriptX applies a document author's desired attributes at the time of printing browser window or framed content, but thereafter automatically restores all default settings and makes no permanent changes.

ScriptX 1.0 was introduced by MeadCo in 1998 as a freely distributable utility offering a limited set of print formatting functionality - the scripted control of the printing of HTML frame or window content (with or without a prompt), and the specification by script of printing parameters such as page headersfootersmarginsand paper orientation within IE.

That basic functionality is still available at no charge and is freely distributable. Features that are part of that 'free' printing subset are marked in this document asbasic.

With the releases of later versions, significantly more advanced printing functionality was introduced which is only accessible in the presence of a paid-for MeadCopublishing license.

Target platform

ScriptX has been tested on and supports Microsoft Windows Web Browsing Platform versions 4.01 SP1 - 7.0 on all Microsoft Windows Win32 OS platforms (including Vista).

ScriptX v6.4 and later no longer support Windows 9x/NT. For maintenance support of these operating systems, please see ScriptX win9xNT/NT Maintainance Mode Binaries.

ScriptX v6.4 and later are supported on all Microsoft Windows client and server platforms from Windows 2000 onwards with Internet Explorer 5.5 or later.

Product credits

ScriptX has been widely adopted and acknowledged by the Web and intranet development communities. Check out:

Summary of examples

    Basic
    Illustrates the straightforward use of the freely distributable ScriptX basic printing functionality: headersfootersmargins and paper orientation.

    Advanced
    Illustrates the typical use of ScriptX advanced printing functionality for which a publishing license is required.

    Techie
    An all-in-one technical example illustrating the most advanced use of licensed ScriptX functionality.
    Printing reports and customised documents
    Provides a discussion of printing customised documents and reports with ScriptX and a number of samples of differing techniques. A download of all the sample code is included.
    Direct printing
    Illustrates direct printing to a Zebra thermal label printer using the ZBL command language, a publishing license is required.

Feel free to investigate the source code from any of the examples and to cut & paste fragments into your own applications.

Advanced control of HTML Printing with ScriptX

Advanced printing functionality can only be used with a paid-for publishing license. Some of the advanced features enabled with a license are:

  • Control over the printing of a document's background color and images (printBackground).

  • SetMarginMeasure method to ensure that the chosen unit of measure for margins (inches or millimeters) will be consistent across machines with different locale settings.

  • Facilities to select a non-default printer, paper size & source, page range & collation and number of copies to print.

  • Reliability and scalability. The PrintHTML(url) method can queue and print any number of documents without compromising system performance. This is especially important for server side printing. On the client side, PrintHTML works in the HTTP session context of the calling page (SSL is supported as well).

  • Precise tracking of spooler activity (IsSpoolingWaitForSpoolingCompleteonafterprint). By default, when the Internet Explorer window is closed or the page navigated away from whilst a print-out is still being spooled, the user will be prompted. The prompt can be customized or disabled (onbeforeunload).

  • Print settings changes (headersbasicfootersbasicmarginsbasicpaper orientationbasicprinter namepaper sizepaper sourcepage range selectionnumber of copiescollationduplex mode) once made from script now become active for Internet Explorer's native UI Print... and Page Setup... commands, as well as for the native window.print() script method, during the time that the document is displayed. Now an author doesn't need to put a [Print] button on an HTML page.

  • Internet Explorer's native printing UI can be trapped and cancelled, or handled in a particular way (disableUIonuserprintonuserpreviewonuserpagesetup). A document's DHTML user interface can also be updated in response to user changes in the Page Setup and Print dialogs (onpagesetup). See the Techie printing example for an illustration of UI handling.

  • All changes made to print settings affect only the current document (in the current tab) when it is printed or previewed. Settings are untouched in other IE windows or tabs and will not apply to any other documents viewed in the current window/tab.

  • A redirect of print data can be made to a specified file name (printToFileName).

  • Basic printing of Microsoft Officetm documents.

  • Printing of PDF documents (PrintPDF and BatchPrintPDF).

Backwards compatibility

All releases of ScriptX are fully backwards compatible with previous releases and for advanced functionality will work with all existing publishing licenses. ScriptX works in close concert with the Microsoft Windows Web Browsing Platform and as a result  is updated to work with all latest releases and patches. All code updates are free; there is never a charge for obtaining the latest code.

We strongly recommend that you update your <OBJECT> elements to reference the current version 7,0,0,8 and update smsx.cab on your servers.

  • An important compatibility issue is that ScriptX printing will always prompt when called in the context of Internet Explorer's Internet Security Zone (check the zone icon in the browser's status bar). This is done to prevent anonymous Internet content invoking printing without a prompt (see PRB: Printing with WebBrowser from Internet Explorer Raises Print Dialog Box in Internet Explorer 5).

    For the My Computer, Local Intranet and Trusted Sites Security Zones promptless printing will work. If you need promptless printing for the Internet Security Zone, you should obtain a publishing license that will bind the deployment of ScriptX to the URL addresses from which you want to serve ScriptX-enabled content.

  • Another important note concerns margin units of measure (inches and millimeters). By default ScriptX uses the units of measure set on the client machine. This is OK when pages are being authored for a known environment such as a small corporate intranet where all Regional Settings are identical, but in a broader environment users' Number settings are certain to vary. So an author should specify the SetMarginMeasure method with a value of either 1 (mm) or 2 (inches). ScriptX will then print to the margins specified regardless of -- and without affecting -- a user's default Regional Number Settings.

What's New Summary

A full listing of the release of ScriptX versions and the modifications they contained is available on the ScriptX History page.

v6.2

Version 6.2 introduces the printerControlJobs and Job objects to provide detailed information about the available printers and control of the print queue for a printer. The use of methods that control the print queue requires that the user has administrator rights on the printer.

Also included in this version is an extension of the MeadCo licensing scheme to provide a usable distribution model and allow the use of ScriptX within desktop applications.

v6.3

Version 6.3 provides support for Internet Explorer 7 on Windows XP and Windows Vista; v6.3 is required on the IE 7 platform ... previous versions of ScriptX arenot compatible.

This release includes a new print template that provides the same functionality as that within Internet Explorer 7 - scale to fit printing by default and enhanced print preview with draggable margins and switchable headers. This template is available for all versions of Internet Explorer from v5.5 so, whilst your users may be running anything from IE 5.5 onwards, you can give them all a consistent print experience.

The use of the new template is optional - by default ScriptX will use the default template for the platform (IE5.5 style on IE 5.5/IE 6 and IE 7 style on IE7. The particular template required can be specified in script using the templateUrl property or may be specified as a parameter to the ScriptX object.

Frames can now be previewed. This was a MaxiPT only feature but is now also included in the Advanced licensed feature set for ScriptX.

A code review has been undertaken with this release, with APIs checked for behaviour and consistency. This has resulted in some cases where in previous releases a property/method would not report an error when an error occurred - errors are now reported. This may necessitate changes to script code if it was assumed that code would run without error.

v6.3.435

From the first build of this version onwards, ScriptX comes in a single signed CAB - smsx.cab. In addition to fixes for a number of issues, this release introduces improvements for application licenses and the ability to install license updates without requesting permission from the user (this will only occur for updates of an already accepted license).

Two new methods are introduced to provide additional control over the behaviour of the new IE 7 style template. These methods require a publishing license:

  • SetPreviewZoom -  provides control over the zoom factor used on print preview.
  • SetPrintScale -  provides control over the scaling used when printing.

v6.3.436

Version 6,3,436 introduces the ability to send raw text to an attached printer. The text is not rendered to the printer, it is interpreted by the printer. This is useful in scenarios such as controlling a thermal label printer. For more information, see rawPrinting.

v6.4

ScriptX v6.4 and later no longer support Windows 9x/NT. For maintenance support of these operating systems, please see ScriptX win9xNT/NT Maintainance Mode Binaries.

This release also introduces Enterprise+ licensing and preliminary support for IE8. Please note that this release has been tested against IE 8 Beta 1 only, there are no known problems other than under Vista where there are a number of small issues which will be addressed in future releases of IE/ScriptX.

v6.5

ScriptX v6.5 and later fully supports IE8 on all supported platforms (Windows 2000 and later). ScriptX 6.5 is a required upgrade for correct operation with IE8.

In support of IE8 one new property has been added: headerFooterFont. Note that scale to fit and print background colours functionality was already included with ScriptX.

A number of problems have also been resolved, including an issue with the SetPageRange() method. Our documentation has been updated to better describe its behaviour. A development history - as well as latest test version of ScriptX - is available on the ScriptX beta page.

v6.6

ScriptX v6.6 introduces a 64-bit Edition for x64 systems and controlled printing of PDF documents with the licensed Corporate 32-bit Edition of ScriptX. ScriptX v6.6 also includes support for Internet Explorer 9 Beta 1 and IE 9 Preview up to Preview 7.

ScriptX 6.6 is a required upgrade for correct operation with IE9.

How do I use the ScriptX object?

Before reading further, please have a look at our illustrative BasicAdvanced and Techie examples of ScriptX printing to get an idea of what ScriptX can do for you.

There are three scenarios in which ScriptX provides the solution for printing of HTML documents with the Microsoft Windows Web Browsing Platform:

  1. Within the Internet Explorer browser, on client-side HTML or XML pages. Here, ScriptX provides full scripted control of the printing experience within IE, allowing choosing the output printer, orientation, page header and footers etc and the initiation of the print. ScriptX is ideal for deployment within web applications hosted within Internet Explorer.
  2. On the server, where ScriptX performs as part of server side request processing, printing an html document loaded from the same or different server.
  3. As part of a desktop application, ScriptX can be used to print HTML documents from the file system, a web server or generated as an 'inline' string.

Note that the use of ScriptX on the server always requires a license. All licenses are available (on request to feedback@meadroid.com) for a trial period to enable full and proper evaluation of the suitability of ScriptX for a particular usage.

Client-side deployment within Internet Explorer (x86 32-Bit Edition).

Typically ScriptX is deployed as a client-side ActiveX control, instantiated and scripted on an HTML or XML page as an <OBJECT> element. Download and installation is a one-time client-side event and is handled automatically by the standard Internet Explorer Component Download technology.

Requirements for a successful installation

  • The end user's system must have the "Download Signed ActiveX Controls" and "Script ActiveX control marked as safe for scripting" security settings enabled for the corresponding Security Zone. These are the default settings for the My ComputerLocal IntranetTrusted Sites and Internet Security Zones.
  • In addition, on Windows 2000 systems and later, the user must be logged on as an Administrator/Power User with the ability to write to the HKEY_LOCAL_MACHINE registry hive and the Windows system folder (typically c:\windows\system32). For Windows Vista and later, the user must be able to complete an Account Control elevation dialog, either through accepting the dialog since they are logged in as an administrator or by entering the user name and password of a suitable administrators account.

Alternative installers (and 64-bit Edition of ScriptX)

If the above requirements cannot be met we suggest that you ask to review our Corporate Resource Kit, a $500-per-year cost-option for licensees which comes as a collection of .msi and merge modules and documentation. The Corporate Kit enables more modern and flexible installation choices than can be provided from our historic .cab-based schema, including the ability to develop a custom installer to requirement using the supplied merge modules.

In addition, the Corporate Resource kit includes the 64 bit Edition of ScriptX. Whilst primarily intended for deployment on server systems for server side printing, the 64 bit Edition can be deployed for use with the 64 bit Edition of Internet Explorer. Please note that, at the time of writing, the default edition of Internet Explorer is 32 bit on all Microsoft Windows operating systems, including 64 bit OSs.

Codebase referencing and use of the object

From the first 6,3,435,x version onwards, ScriptX comes as standard in a single signed CAB - smsx.cab - which is part of a download package obtainable from theScriptX site. The CAB file should be placed on the web server and its location should be referenced by the CODEBASE attribute of the <OBJECT> tag, as shown below.

NOTE: In your own code, we recommend that you place the ScriptX <OBJECT> elements in the document's <BODY> container.

  • Make sure that you provide the correct relative or fully-qualified path to the CAB file and the correct version info (7,0,0,8) in your CODEBASE attributes.

  • Start to script the ScriptX object only when the page is fully loaded i.e. once the window.onload event has occured.

  • Use the defer attribute where appropriate in your scripts: <SCRIPT defer>...<SCRIPT> and avoid immediate script statements (i.e. code which is outside of any function scope). This is an under-appreciated but very useful feature which instructs the script to execute only when the whole document's DHTML content is completely parsed. This way you can be sure of accessing every element on the page.

  • The 'de-facto' standard, started by this documentation is to use the id 'factory' for the ScriptX object. Any id that is desired may be used.

  • For simplicity, these documents directly refer to the object via its id rather than using document.getElementById(). Either approach is acceptable; if the samples are inspected via View Source it will be seen that the jQuery library is used in the samples, along with a wrapper class to safely access the ScriptX object. The use of jQuery etc is also entirely optional.

The following code snippets assumes that smsx.cab exists in the same folder as the hosting page itself.

Basic functionality:

<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
  codebase="smsx.cab#Version=7,0,0,8">
</object>

The Basic printing example illustrates the use of the basic printing subset.

The viewastext attribute prevents an authoring tool such as Microsoft FrontPagetm or Visual InterDevtm from running the object at design time. This attribute is not required if you do not use these tools and note that it can cause problems in some environments; for example strict xhtml documents.

NOTE: with the 'basic' subset, you can only script headerfooterpage marginspaper orientationPrint and PageSetup methods and properties.

Specifying a template (e.g. IE 7)

With version 6.3 and later, you may specify the template to use; this is particularly useful when wishing to provide the Internet Explorer style template (default scaled to fit printing) to users with IE 5.5/6.0 browsers or when specifying the use of the MaxiPT template.

<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
  codebase="smsx.cab#Version=7,0,0,8">
	<param name="template" value="MeadCo://IE7" />
</object>

The ability to specify a particular in-built template is included in the 'basic' subset.

Advanced functionality:

<!-- MeadCo Security Manager -->
<object viewastext style="display:none"
  classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
  codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id=factory viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

NOTE: the {0ADB2135-6917-470B-B615-330DB4AE3701} value of the GUID parameter used above identifies the MeadCo evaluation license that authors may use to experiment with Advanced printing capabilities. The license validates local filesystem (file://) and local website (http://localhost/) content for evaluation purposes only on a single development computer.

The evaluation license is periodic. It will expire in a few months and will be replaced by a new one with a different GUID, so any code depending on the evaluation license may suddenly stop working at any time.

Registered customers are issued with an unique license identifier and a digitally signed sxlic.mlf license file. See the licensing page for more details.

Check out the sources of the Advanced and Techie printing examples for a complete illustration of how to use licensed ScriptX functionality. The following JScript code snippet shows how to modify printing settings so as to print to a specific printer:

<script defer>
function SetPrintSettings() {
  // -- advanced features
  factory.printing.SetMarginMeasure(2); // measure margins in inches
  factory.printing.printer = "HP DeskJet 870C";
  factory.printing.paperSize = "A4";
  factory.printing.paperSource = "Manual feed";
  factory.printing.collate = true;
  factory.printing.copies = 2;
  factory.printing.SetPageRange(false, 1, 3); // need pages from 1 to 3

  // -- basic features
  factory.printing.header = "This is MeadCo";
  factory.printing.footer = "Advanced Printing by ScriptX";
  factory.printing.portrait = false;
  factory.printing.leftMargin = 1.0;
  factory.printing.topMargin = 1.0;
  factory.printing.rightMargin = 1.0;
  factory.printing.bottomMargin = 1.0;
}

function Print(frame) {
  factory.printing.Print(true, frame) // print with prompt
}
</script>

A subtle JScript syntax issue may occur when setting a printer name that contains back slashes. Don't forget to double the slashes:

factory.printing.printer = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

How to check whether or not the object is properly installed

Upon the window.onload event, test whether or not the object property of the ScriptX or the Security Manager object returns as a valid object. The way to do that is shown in the script snippet below.

In the event that you experience any problems with automatic client-side download and installation, check out HOWTO: Find More Information About Why Code Download Failed and Description of Internet Explorer Security Zones Registry Entries as part of your troubleshooting.

<!-- MeadCo Security Manager - using the evaluation license -->
<object id="secmgr" viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  if ( !factory.object ) {
    alert("MeadCo's ScriptX Control is not properly installed!");
    navigate("scriptx-install-error.htm");
    return;
  }
  if ( !secmgr.object ) {
    alert("MeadCo's Security Manager Control is not properly installed!");
    navigate("secmgr-install-error.htm");
    return;
  }
  if ( !secmgr.validLicense ) {
    alert("The MeadCo Publishing License is invalid or has been declined by the user!");
    navigate("license-error.htm");
    return;
  }
  alert("Ready to script MeadCo's ScriptX!")
}
</script>

Testing your print-outs

The development and testing of code to produce good-looking printed reports usually takes a number of iterations. To save toner, paper, trees and our own precious time :-) we regularly use the FinePrinttm application from FinePrint Software.

FinePrinttm installs a virtual printer driver that serves as indirection layer between the printing application (Internet Explorer in our case) and a physical or networked printer. In 'bypass' mode it lets us accurately preview and repaginate ScriptX-enabled content before it is actually printed or discarded.

It's also a very handy testing device with which to diagnose printing problems. So because we are physically unable to test ScriptX with every model and version of printer and printer driver that exists in the world, we would greatly appreciate it if you would try printing to the FinePrint driver before reporting errors against ScriptX from your particular printing environment.

NOTE: Mead & Co Limited has no commercial affiliation with FinePrint Software, LLC.

Working with Visual Studio and ASP.NET

The samples on this site are implemented using ASP.NET and the MVC extensions. The samples system is used in various locations, including the Infopages where the latest release, hotfixes and development versions of ScriptX may be obtained. The samples system itself provides a compreshensive set of demonstrations of the capabilities and working of ScriptX under all document types and modes.

When working with ASP.NET we recommend creating a server-side control or for MVC a partial view that will outout the various object tags required by ScriptX. We recommend values such as codebase location and version are obtained from AppSettings stored in web.config.

Please note that when working with ASP.NET Forms we recommend that the ScritpX objects are placed outside the <form /> element.

Technical support

Licensees of ScriptX' advanced printing functionality are entitled to unlimited direct-to-company email support and access to new versions of the ScriptX software as-and-when issued, both at no additional charge.

Please send us feedback & bug reports.

Web support links

Microsoft Internet Explorer printing and Internet Explorer Component Download support articles:

INFO: WebCast: How Does Internet Component Download Work?

HOWTO: Find More Information About Why Code Download Failed

PRB: Trust Provider Warning Message Appears When You Attempt to Download Components

PROBLEM: Blank Page Is Printed in Internet Explorer 5.5

General information on Internet Explorer printing:

Beyond Print Preview: Print Customization for Internet Explorer 5.5

Print Preview 2: The Continuing Adventures of Internet Explorer 5.5 Print Customization

Print Template Reference

Style Sheets and Printing횂쨩

Inside Technique : Printing Techniques횂쨩

Printing Tables on Multiple Pages

INFO: Page Break Styles Supported Only with Block Elements


ScriptX printing: technical reference

Unless otherwise indicated by the basic icon, the use of any property or method requires a publishing license.

Objects

BinsFormsfactoryprintingprinterControlJobsJobrawPrinting

Properties

attributesbottomMargincollatecopiescurrentPrinterdisableUIduplexfooterheaderheaderFooterFontisLocalisNetworkisSharedJobsleftMargin,locationnameonafterprintonbeforeunloadonpagesetuponuserpagesetuponuserprintonuserprintpreviewpageHeightpageWidthpaperSizepaperSource,port,  portraitprintBackgroundprinterprinter (direct printing), printerControlprintToFileNamerightMarginserverNameshareNamestatustemplateURL,topMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

Methods and Functions

BatchPrintPDFDeleteDefaultPrinterEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueuePageSetup,PausePreviewPrintPrintDocumentPrintHTMLPrintPDFPrintSetupPrintStringPurgeRestartResumeSetMarginMeasureSetPageRangeSetPrintScale,SetPreviewZoomSleepWaitForSpoolingComplete

Objects

Bins


Description

Lists the available paper sources for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScriptfor..each loop).

The names returned are suitable for use with the paperSource property.

Syntax

oJobs = printerControl.Bins

Properties

Item(nIndex) - returns the name of the paper source item at nIndex
Count - returns the number of available paper sources.

Methods

None.

Example

<script defer>
function listBins() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Bins;
	var e = new Enumerator(j);
	var s = "";
	while ( !e.atEnd() ) {
		if ( s.length > 0 ) s+="\n";
		s += e.item(0);
		e.moveNext();
	}
	alert("There are " + j.Count + " available sources:\n\n" + s);
}
<script>

Applies To

printerControl

See Also

paperSource

Forms


Description

Lists the available paper sizes (forms) for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScriptfor..each loop).

The names returned are suitable for use with the paperSize property.

Syntax

oJobs = printerControl.Forms

Properties

Item(nIndex) - returns the name of the paper at nIndex
Count - returns the number of available paper sizes.

Methods

None.

Example

<script defer>
function listForms() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Forms;
	var e = new Enumerator(j);
	var s = "";
	while ( !e.atEnd() ) {
		if ( s.length > 0 ) s+="\n";
		s += e.item(0);
		e.moveNext();
	}
	alert("There are " + j.Count + " available paper sizes:\n\n" + s);
}
<script>

Applies To

printerControl

See Also

paperSize

factory


Description

Represents the ScriptX object itself on an HTML page for scripting by its id . For historical reasons, we name it factory.

For WSH or ASP (i.e. server-side) use only, create a ScriptX instance dynamically with the JScript new ActiveXObject횂쨩 or the VBScript CreateObject횂쨩.

Note that you can not use CreateObject or new ActiveXObject to call ScriptX client-side. You should call ScriptX in all client-side cases by the id of the on-page ScriptX object.

See How do I use the ScriptX object for deployment details.

Examples

HTML page:

<object id=factory viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
codebase="smsx.cab#Version=7,0,0,8">
</object>

WSH script (JScript):

var factory = new ActiveXObject("ScriptX.Factory")
factory.printing.PrintHTML("http://msdn.microsoft.com/workshop/author/script/dhtmlprint.asp")

ASP page (VBScript):

<%
 set factory = CreateObject("ScriptX.Factory")
 factory.printing.PrintHTML "http://localhost/orders/order.asp?number=" & Request.Form("number")
 set factory = nothing
%>

Properties

printingrawPrinting

printing


Description

Represents the printing functionality of ScriptX. See HTML Printing with ScriptX for more information and examples.

Syntax

printing = factory.printing

Properties

bottomMargincollatecopiescurrentPrinterdisableUIduplexfooterheaderheaderFooterFontleftMarginonafterprintonbeforeunload,onpagesetuponuserpagesetuponuserprintonuserprintpreviewpageHeightpageWidthpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

Methods

BatchPrintPDFDefaultPrinterDoPrintEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueue,PageSetupPreviewPrintPrintHTMLPrintPDFPrintSetupPrintXMLSetMarginMeasureSetPageRangeSetPrintScaleSetPreviewZoomSleep,WaitForSpoolingComplete

Applies To

factory

printerControl


Description

Represents the ability to determine a range of printer properties and control the print queue for the printer. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the string does not exist or is written incorrectly then an error will be thrown (e.g. "The printer name is invalid").

Syntax

oControl = factory.printing.printerControl(sPrinterName)

Properties

attributesBinsFormsisLocalisNetworkisSharedJobslocationnameport,  serverNameshareNamestatus

Methods

PausePurgeRestartResume

Example

<script defer>
function networkServer() {
	var oControl = factory.printing.printerControl(factory.printing.currentPrinter);
	if ( oControl.isNetwork )
		alert("The current printer is on the network server: " + oControl.serverName);
}
<script>

Applies To

printing

rawPrinting (v6.3.436 and later)


Description

Represents the direct printing from within Internet Explorer functionality of ScriptX. Version 6.3.436 or later of ScriptX is required.

Note: Direct printing is a cost-option which can be enabled on a 'standard' client-side license for an additional fee of $500.

Direct printing allows for printing to programmable devices such as thermal label printers, whereby a label string can be sent directly to the printer. The Internet Explorer print engine is not used and takes no part in the process. The functionality available from rawPrinting is completely separate from that available from the printing object, and for this reason settings such as printerpaper sizeorientation, etc. that may have been set on the printing object for Internet Explorer do not apply to the rawPrinting object.

NOTE: rawPrinting is not supported in any form of usage outside of Internet Explorer.

Syntax

raw = factory.rawPrinting

Properties

printer

Methods

printStringprintDocument

Applies To

factory

Jobs


Description

Represents the list of jobs currently in the queue for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScript for..each loop).

Syntax

oJobs = printerControl.Jobs

Properties

Item(nIndex) - returns a printJob object for the item at nIndex
Count - returns the number of items in the queue.

Methods

None.

Example

<script defer>
function listJobs() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Jobs;
	var e = new Enumerator(j);
	alert("There are " + j.Count + " jobs in the queue");
	while ( !e.atEnd() ) {
		alert("Job name: " + e.item().document);
		e.moveNext();
	}
}
<script>

Applies To

printerControl

See Also

EnumJobsGetJobsCount

Job


Description

Represents a single job in the queue for a printer. A job is obtained from the list of print jobs available on a printer.

Syntax

oJob = printerControl.Jobs.Item(nIndex)

Properties

All properties are read only:

PropertyDescripion
documentSpecifies the name of the print job, typically the title of the html document that has been printed.
machineNameSpecifies the name of the machine that created the print job.
pagesPrintedSpecifies the number of pages that have printed. This value may be zero if the print job does not contain page delimiting information.
positionSpecifies the job's position in the print queue.
printerNameSpecifies the name of the printer for which the job is spooled.
sizeSpecifies the size, in bytes, of the job.
statusSpecifies the job status, can be one or more of the following values:
MeaningValue
JOB_STATUS_PAUSED0x00000001
JOB_STATUS_ERROR0x00000002
JOB_STATUS_DELETING0x00000004
JOB_STATUS_SPOOLING0x00000008
JOB_STATUS_PRINTING0x00000010
JOB_STATUS_OFFLINE0x00000020
JOB_STATUS_PAPEROUT0x00000040
JOB_STATUS_PRINTED0x00000080
JOB_STATUS_DELETED0x00000100
JOB_STATUS_BLOCKED_DEVQ0x00000200
JOB_STATUS_USER_INTERVENTION0x00000400
JOB_STATUS_RESTART0x00000800
statusTextA string containing a description of the status. This may be provided by the printer driver or may be generated by ScriptX from the value of status. If generated by ScriptX the description is in English only.
submittedAtSpecifies the time when the job was submitted.
totalPagesSpecifies the number of pages required for the job. This value may be zero if the print job does not contain page delimiting information.
userNameSpecifies the name of the user who owns the print job.

The value of all properties are determined at the time that the Jobs collection is created, no properties are dynamic (for example a loop inspecting the value of pagesPrinted will not see the value decrease as might be expected).

Methods

DeletePauseRestartResume

Properties

attributes


Description

Returns the attributes of the printer; can be any reasonable combination of the following values:

ValueMeaning
PRINTER_ATTRIBUTE_DEFAULT (0x00000004)Windows 95/98/Me: Indicates the printer is the default printer in the system.
PRINTER_ATTRIBUTE_DIRECT (0x00000002)Job is sent directly to the printer (it is not spooled).
PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST (0x00000200)If set and printer is set for print-while-spooling, any jobs that have completed spooling are scheduled to print before jobs that have not completed spooling.
PRINTER_ATTRIBUTE_ENABLE_BIDI (0x00000800)Windows 95/98/Me: Indicates whether bi-directional communications are enabled for the printer.
PRINTER_ATTRIBUTE_FAX (0x00004000)Windows XP: If set, printer is a fax printer. 
PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS (0x00000100)If set, jobs are kept after they are printed. If unset, jobs are deleted.
PRINTER_ATTRIBUTE_QUEUED (0x00000001)If set, the printer spools and starts printing after the last page is spooled. If not set and PRINTER_ATTRIBUTE_DIRECT is not set, the printer spools and prints while spooling.
PRINTER_ATTRIBUTE_SHARED (0x00000008)Printer is shared.
PRINTER_ATTRIBUTE_WORK_OFFLINE (0x00000400)Windows 95/98/Me: Indicates whether the printer is currently connected. If the printer is not currently connected, print jobs will continue to spool.
PRINTER_ATTRIBUTE_PUBLISHED (0x00002000)Windows 2000/XP: Indicates whether the printer is published in the directory service.
PRINTER_ATTRIBUTE_NETWORK (0x00000010)Printer is a network printer connection.
PRINTER_ATTRIBUTE_LOCAL (0x00000040)Printer is a local printer.
PRINTER_ATTRIBUTE_RAW_ONLY (0x00001000)Indicates that only raw data type print jobs can be spooled.

 

Syntax

attributes = printerControl.attributes

Settings

This is a read only property.

Applies To

printerControl

bottomMarginbasic


Description

Specifies the bottom margin height for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableBottom), in which case it will be automatically corrected to the minimum allowed value. If top and bottom margins are set to overlap, they will be corrected to an arbitrary default value of 1/10 of page height.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The bottomMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.bottomMargin = numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

leftMarginpageHeightpageWidthportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

collate


Description

Specifies whether or not to collate the pages of HTML print-outs when more than one copy is printed.

Syntax

printing.collate = true|false

Settings

This is a read/write property. Use true to collate.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

duplexprinter

PrintPrintHTMLPrintSetup

copies


Description

Specifies the number of copies for HTML print-outs.

Syntax

printing.copies = numCopies

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

collateduplexprinter

PrintPrintHTMLPrintSetup

currentPrinter


Description

Specifies the printer to print to. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the string does not exist or is written incorrectly, printing will be directed to the default printer.

Syntax

printing.currentPrinter = sPrinterName

Settings

This a read/write property. With JScript, take care to double a backslash if one appears in the printer name, as in the example below.

Usage

The internal implementation of writing to the currentPrinter property is the same as writing to the printer property, other than the implementation ofcurrentPrinter does not 'eat' any error. Therefore an error in currentPrinter will be reported in the same way as any other error that occurs in an ActiveX object property/method call.

Example

factory.printing.currentPrinter = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

Applies To

printing

See Also

HTML Printing with ScriptX

printerEnumJobsEnumPrintersGetJobsCountIsTemplateSupportedPrint

 

disableUI


Description

Set to true to disable all of Internet Explorer's printing facilities, including the File/Page Setup, File/Print main menu commands, the Print context menu command and the window.print() scripting method. Given this, the only way left to print is via the ScriptX Print and PrintHTML methods.

Syntax

printing.disableUI = true|false

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing example.

See Also

HTML Printing with ScriptX

onpagesetuponuserpagesetuponuserprintonuserprintpreview

PageSetupPreviewPrintPrintSetup

duplex


Description

Duplex mode (if supported by the targeted printer).

Syntax

printing.duplex = number

Settings

This is a read/write property. Use for simplex mode (no duplex), for vertical duplex, for horizontal duplex.

Applies To

printing

See Also

HTML Printing with ScriptX

collatecopies

PrintPrintHTMLPrintSetup,

footerbasic


Description

Specifies the string to be used as the footer for HTML print-outs. String can include Internet Explorer header/footer metasymbols. If you need to use HTML for your headers and footers, check MaxiPT 1.0횂쨩 (Internet Explorer 5.5 or later).

The footer property is part of the basic freely-distributable printing subset.

Syntax

printing.footer = sFooter

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

header

headerFooterFont

PageSetupPrintPrintHTML

headerbasic


Description

Specifies the string to be used as the header for HTML print-outs. String can include Internet Explrore header/footer metasymbols. If you need to use HTML for your headers and footers, check MaxiPT 1.0횂쨩 (Internet Explorer 5.5 or later).

The header property is part of the basic freely-distributable printing subset.

To print specific information as part of the header or footer, include the following characters as part of the string:

ShorthandMeaning
&wWindow title
&uPage address (URL)
&dDate in short format (as specified by Regional Settings in Control Panel)
&DDate in long format (as specified by Regional Settings in Control Panel)
&tTime in the format specified by Regional Settings in Control Panel
&TTime in 24-hour format
&pCurrent page number
&PTotal number of pages
&&A single ampersand (&)
&bThe text immediately following these characters as centered.
&b&bThe text immediately following the first "&b" as centered, and the text following the second "&b" as right-justified.

Syntax

printing.header = sHead

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

footer

headerFooterFont

PageSetupPrintPrintHTML

headerFooterFontbasic


Description

From version 6.5.439, ScriptX supports retrieving and specifying the font used to render the document header and footer. The use of this feature requires Internet Explorer 8 or later.

Specifies or retrieves the description of the font to use. The font is described using a css style definition, one or more of the following semicolon-delimited values:

ValueDescription
font-familyThe font family name to use.
font-sizeThe size to use, units should be pixels.
colorThe colour for rendering the text, given as an RGB value - for example, rgb(255,0,0)
font-weightThe weight of the font as normal or bold
font-styleThe font style, as italicnormal, or oblique

Note: No error is thrown if this property is used with versions of Internet Explorer prior to 8 - settings are simply ignored.

Syntax

printing.headerFooterFont sFontSpec

Settings

This a read-write property.

Applies To

printing

Example

factory.printing.headerFooterFont = "font-family: Comic Sans MS; font-size: 10px; color: rgb(0,128,0); font-weight: bold;"

See Also

headerfooter

isLocal


Description

Returns whether the printer is a local printer (true) or not (false). isLocal tests whether PRINTER_ATTRIBUTE_LOCAL is set in the attributes.

Syntax

bIs = printerControl.isLocal

Settings

This is a read only property.

Applies To

printerControl

isNetwork


Description

Returns whether the printer is a network printer (true) or not (false). isNetwork tests whether PRINTER_ATTRIBUTE_NETWORK is set in the attributes.

Syntax

bIs = printerControl.isNetwork

Settings

This is a read only property.

Applies To

printerControl

isShared


Description

Returns whether the printer is a shared printer (true) or not (false). isShared tests whether PRINTER_ATTRIBUTE_SHARED is set in the attributes.

Syntax

bIs = printerControl.isShared

Settings

This is a read only property.

Applies To

printerControl

leftMarginbasic


Description

Specifies the left margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableLeft), in which case it will be automatically corrected to the minimum allowed value. If left and right margins overlap, they will be corrected to an arbitrary default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The leftMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.leftMargin numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

pageHeightpageWidthportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

location


Description

Returns a string describing the physical location of the printer.

Syntax

sLoc = printerControl.location

Settings

This is a read only property.

Applies To

printerControl

name


Description

Returns a string giving the name of the printer.

Syntax

sName = printerControl.name

Settings

This is a read only property.

Applies To

printerControl

onafterprint


Description

Event handler to be called when print spooling is done. The event is applicable to the results of a Print call but not to that of a PrintHTML call. It can be used to update the user interface accordingly. It is similar to the WaitForSpoolingComplete blocking call, but is asynchronous.

Note the difference between ScriptX's onafterprint event and the DHTML window.onafterprint event: the latter occurs after Internet Explorer has just made a document snapshot for printing and not after the actual print spooling job (see PRB: onafterprint Event Fires Before the Print Dialog Box Appears). So these two events are not interchangeable.

In fact, the DHTML window.onbeforeprint and window.onafterprint exist to give the document's script a chance to customize DHTML content before it goes to print-out or preview (and not to signal actual printing). The same effect can be achieved with the CSS  media=print or media=screen specific styles. Check out the following InsideDHTML.com articles: Printing TechniquesUsing CSS to specify alternate document to print out.

Syntax

printing.onafterprint = function_object

Settings

This is a read/write property.

Applies To

printing

Example

<script defer>
factory.printing.onafterprint = AfterPrint;

function AfterPrint() {
  alert("The document has been sent to the print spooler!");
}
</script>

See Also

HTML Printing with ScriptX

onpagesetuponuserpagesetuponuserprintonuserprintpreview

PrintWaitForSpoolingComplete

onbeforeunload


Description

String to prompt a user with when spooling (or a download originated by a PrintHTML call) is still in progress but the page is being closed or navigated away. By default, ScriptX waits 5 seconds in blocking mode to let spooling complete, then prompts the user with the choice to cancel the printing process. The user may decide to wait for another 5 seconds, and so on.

Note: to suppress the prompt you can force the blocking wait state with WaitForSpoolingComplete after any Print or PrintHTML call or before leaving the page. However the use of WaitForSpoolingComplete() after each PrintHTML call in a sequence of calls is not recommended. Use it only after the last call in the sequence.

Syntax

printing.onbeforeunload = string

Settings

This is a read/write property.

Applies To

printing

See Also

HTML Printing with ScriptX

PrintPrintHTMLWaitForSpoolingComplete

onpagesetup


Description

Event handler to be called when the current print or page setup settings are changed on the Internet Explorer Page Setup dialog. 

Use it to update the page's user interface accordingly. This is exactly what the ScriptX Techie Printing example does.

Syntax

printing.onpagesetup = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonuserpagesetuponuserprintonuserprintpreview

PageSetup

onuserpagesetup


Description

Event handler to be called when a user invokes the Page Setup... command from Internet Explorer's File menu. 

You may cancel this operation within the event handler simply by returning, or you may call PageSetup to provide the expected behavior. In the latter case, once the user has made changes on the Page Setup dialog an onpagesetup event will be fired to update the page's user interface. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserpagesetup = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserprintonuserprintpreview

PageSetup

onuserprint


Description

Event handler to be called when a user invokes the Print... command from the Internet Explorer File menu, or presses Print on the document's right-click context menu, or hits the printer button on the toolbar, or presses the Ctrl-P key combination, or when a script calls window.print().

You may cancel this operation within the event handler simply by returning, or you may call Print to provide the expected behavior. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserprint = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserpagesetuponuserprintpreview

PageSetup

onuserprintpreview


Description

Event handler to be called when a user invokes the Preview... command from the Internet Explorer File menu or hits the print preview button on the toolbar.

You may cancel this operation within the event handler simply by returning, or you may call Preview to provide the expected behavior. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserprintpreview = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserpagesetuponuserprint

PageSetup

pageHeight


Description

Returns the physical height of the current printer paper selection.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

Syntax

height = printing.pageHeight

Settings

This is a read-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageWidthpaperSizeportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

PageSetupSetMarginMeasure

pageWidth


Description

Returns the physical width of the current printer paper selection.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

Syntax

width = printing.pageWidth

Settings

This is a read-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpaperSizeportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupSetMarginMeasure

paperSize


Description

Specifies the paper size for HTML print-outs by its string name. ScriptX tries to find the longest string match amongst the list of available paper size names for the current printer. Read back the paperSize value to see the actual result.

Syntax

printing.paperSize = sPaperSize

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

FormspageHeightpageWidthpaperSourceportraitunprintableBottomunprintableLeftunprintableRightunprintableTop

PageSetupPrintPrintHTMLPrintSetup,

paperSource


Description

Specifies the paper source (tray) for HTML print-outs by its string name. ScriptX tries to find the longest string match amongst the list of available paper source names for the current printer. Read back the paperSource value to see the actual result.

Syntax

printing.paperSource = sPaperSource

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

BinspaperSize

PageSetupPrintPrintHTMLPrintSetup

port


Description

Returns a string string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port will be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

Windows 95/98/Me: This member can specify only one port because multiple ports per printer are not supported.

Syntax

sName = printerControl.port

Settings

This is a read only property.

Applies To

printerControl

portraitbasic


Description

Specifies the page orientation for HTML print-outs.

The portrait property is part of the basic freely-distributable printing subset.

Syntax

printing.portrait = true|false

Settings

This is a read/write property. Use true to specify portrait and false for landscape.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetemplateURLtopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupPrintPrintHTMLPrintSetup

printBackground


Description

Specifies whether or not to print a page's background colors and images.

Syntax

printing.printBackground = true|false

Settings

This is a write-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

PreviewPrintPrintHTML

printer


Description

Specifies the printer to print to. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the printer specified does not exist or is written incorrectly, printing will be directed to the default printer.

Syntax

printing.printer = sPrinterName

Settings

This a write-only property. With JScript, take care to double a backslash if one appears in the printer name, as in the example below.

Please note that providing an invalid name will not raise an error - the request will be ignored and the printer to use remain unchanged. To trap errors specifying the printer to use, use the currentPrinter property.

Applies To

printing

Example

factory.printing.printer = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

Also check out the source code of the ScriptX Techie Printing example.

SSee Also

HTML Printing with ScriptX

rawPrinting

bottomMargin,collatecopiescurrentPrinterduplexfooterheaderleftMarginpaperSizepaperSourceportraitprintBackgroundprintToFileName,rightMargintemplateURLtopMargin

DefaultPrinterEnumJobsEnumPrintersGetJobsCountIsSpoolingIsTemplateSupportedPrintHTMLPrintSetupSetPageRange,WaitForSpoolingComplete

printer  (v6.3.436 and later)


Description

Specifies the printer to directly print to. Only the exact printer name strings as they appear in the Printers Control Panel may be used.

Syntax

rawPrinting.printer = sPrinterName

Settings

This a read-write property. With JScript, take care to double a backslash if one appears in the printer name.

Please note that an error will be thrown if the printer cannot be connected to.

Applies To

rawPrinting

Example

factory.rawPrinting.printer = "Zebra  LP2844-Z"

See Also

printStringprintDocument

 

printToFileName


Description

The file name to print to. Use the full path specification. The file created doesn't accumulate subsequent print-outs and - for security reasons - doesn't get overwritten if it already exists. Specify a new filename for each new print-out.

Printing to file name is supported for Internet Explorer 5.0 and later.

Syntax

printing.printToFileName = sPathFileName

Settings

This is a read/write property. With JScript, take care to double a backslash if one appears in the file path, as in the example below. An empty string indicates that the print-out should go to the printer driver.

Applies To

printing

Example

factory.printing.printToFileName = "d:\\temp\\printout.prn"

See Also

HTML Printing with ScriptX

printer

IsSpoolingPrintPrintHTMLPrintSetupWaitForSpoolingComplete

rightMarginbasic


Description

Specifies the right margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableRight), in which case it will be automatically corrected to the minimum allowed value. If left and right margins overlap, they will be corrected to an arbitrary default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The rightMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.rightMargin numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

pageHeightpageWidthportraitleftMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

serverName


Description

Returns a string giving the name of the server computer controlling the printer. If the string is empty then the printer is controlled locally.

Syntax

sName = printerControl.serverName

Settings

This is a read only property.

Applies To

printerControl

shareName


Description

Returns a string identifying the share point of the printer. This value is only present if PRINTER_ATTRIBUTE_SHARED is set on attributes.

Syntax

sName = printerControl.shareName

Settings

This is a read only property.

Applies To

printerControl

status


Description

Specifies the status of the printer, it can be any reasonable combination of the following values.

ValueMeaning
PRINTER_STATUS_BUSY (0x00000200)The printer is busy.
PRINTER_STATUS_DOOR_OPEN (0x00400000)The printer door is open.
PRINTER_STATUS_ERROR (0x00000002)The printer is in an error state.
PRINTER_STATUS_INITIALIZING (0x00008000)The printer is initializing.
PRINTER_STATUS_IO_ACTIVE (0x00000100)The printer is in an active input/output state
PRINTER_STATUS_MANUAL_FEED (0x00000020)The printer is in a manual feed state.
PRINTER_STATUS_NO_TONER (0x00040000)The printer is out of toner.
PRINTER_STATUS_NOT_AVAILABLE (0x00001000)The printer is not available for printing.
PRINTER_STATUS_OFFLINE (0x00000080)The printer is offline.
PRINTER_STATUS_OUT_OF_MEMORY (0x00200000)The printer has run out of memory.
PRINTER_STATUS_OUTPUT_BIN_FULL (0x00000800)The printer's output bin is full.
PRINTER_STATUS_PAGE_PUNT (0x00080000)The printer cannot print the current page.

Windows 95/98/Me: Indicates the page is being "punted" (that is, not printed) because it is too complex for the printer to print.

PRINTER_STATUS_PAPER_JAM (0x00000008)Paper is jammed in the printer
PRINTER_STATUS_PAPER_OUT (0x00000010)The printer is out of paper.
PRINTER_STATUS_PAPER_PROBLEM 0x00000040)The printer has a paper problem.
PRINTER_STATUS_PAUSED (0x00000001)The printer is paused.
PRINTER_STATUS_PENDING_DELETION (0x00000004)The printer is being deleted.
PRINTER_STATUS_POWER_SAVE (0x01000000)The printer is in power save mode.
PRINTER_STATUS_PRINTING (0x00000400)The printer is printing.
PRINTER_STATUS_PROCESSING (0x00004000)The printer is processing a print job.
PRINTER_STATUS_SERVER_UNKNOWN (0x00800000)The printer status is unknown.
PRINTER_STATUS_TONER_LOW (0x00020000)The printer is low on toner.
PRINTER_STATUS_USER_INTERVENTION (0x00100000)The printer has an error that requires the user to do something.
PRINTER_STATUS_WAITING (0x00002000)The printer is waiting.
PRINTER_STATUS_WARMING_UP (0x00010000)The printer is warming up.

Syntax

printerControl.status = nStatus

Settings

This is a read/write property. The user will require printer administrator writes in order to update the status.

Applies To

printerControl

templateURLbasic (v6.3 and later)


Description

 

For ScriptX v6.3 and later, this property is available as basic  property, the value set must be one of the following special values:

ValueDescription
MeadCo://IE55The IE 5.5/IE 6 style template - note can be used on IE 7.
MeadCo://IE7The IE 7 style template - note free usage on all versions of IE 5.5 or later.
MeadCo://DefaultThe default template for the IE version in use, i.e. the template matches the browser version. This is the default behaviour.
MeadCo://maxiptThe MaxiPT template (requires a license).

Syntax

printing.templateURL templateURL

Settings

This is a read/write property.

Applies To

printing

See Also

 PrintPrintHTML

topMarginbasic


Description

Specifies the top  margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableTop), in which case it will be automatically corrected to the minimum allowed value. If top and bottom margins overlap, they will be corrected to default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The topMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.topMargin = numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

leftMarginpageHeightpageWidthportraitrightMarginbottomMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

unprintableBottom


Description

Returns the bottom unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the bottom edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableBottom

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableLeftunprintableRightunprintableTop

PageSetupPrintPrintSetup

unprintableLeft


Description

Returns the left unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the left edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableLeft

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableRightunprintableTop

PageSetupPrintPrintSetup

unprintableRight


Description

Returns the right unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the right edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableRight

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableLeftunprintableTop

PageSetupPrintPrintSetup

unprintableTop


Description

Returns the top unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the top edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableTop

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableLeftunprintableRight

PageSetupPrintPrintSetup



Methods and Functions

BatchPrintPDF (ScriptX Corporate 32 bit Edition)


Description

Downloads Adobe Acrobattm or Microsoft Officetm files and prints them out in batch mode in the background. Any number of print-outs can be queued.

For Microsoft Officetm files, BatchPrintPDF prints only on the default printer using default settings.

For Adobe Acrobattm files, relevant current printing settings are used as described in the syntax section.

This updated functionality now requires v6.6 or later of ScriptX Corporate 32-bit Edition and an Enhanced PDF Printing license.

Please contact MeadCo sales for details.

Use IsSpooling to check if there are any outstanding downloads in the queue created by BatchPrintPDF. Use WaitForSpoolingComplete to wait for all documents to be downloaded and spooled.

Syntax

printing.BatchPrintPDF(url)

ParameterDescription
urlThe url of the document to be printed.

For Adobe Acrobattm files, the following printing settings are used:

printing.printer
printing.paperSize
printing.paperSource
printing.portrait
printing.copies
printing.collate
printing.duplex
printing.SetPrintScale(-1). 
    [The use of SetPrintScale(-1) enables "Shrink to Fit" of the printed output. Also, rotate pages to fit on the output medium, and center on the page is set. Any other value given to SetPrintScale is ignored.] printing.SetPageRange(false,startPage,endPage) to set the page range to print.

These settings are used per file submitted to the batch, so each document can be printed using different settings, for example, each document to a different printer.

Example

Here is a basic example of BatchPrintPDF use

<body>
<script>
function BatchPrintPDF(url) {
  factory.printing.SetPrintScale(-1); // ensure shrinks to fit if needed
  factory.printing.BatchPrintPDF(url);
}
</script>
<button id="idPrint" onclick="BatchPrintPDF('report.pdf')">BatchPrintPDF('report.pdf')</button>
</body>

Applies To

printing

See Also

HTML Printing with ScriptX

DefaultPrinterEnumJobsEnumPrintersGetJobsCountIsSpoolingPrintHTMLPrintPDFSleepWaitForSpoolingComplete

DefaultPrinter


Description

Returns the name of the default printer (if any).

Syntax

printerName = printing.DefaultPrinter()

Applies To

printing

See Also

HTML Printing with ScriptX

printer

EnumJobsEnumPrintersGetJobsCountIsTemplateSupportedPrint

DoPrint


Description

The alias for the Print method (retained for compatibility reasons).

Applies To

factory

See Also

printingPrintPrintHTML

EnumJobs


Description

Enumerates active jobs on the given printer.

Syntax

var jobName = {}
status = printing
.EnumJobs(printerName, index, jobName)

ParameterDescription
printerName(String) printer name on which to enumerate the jobs
index(Number) Zero-based index of the job. Increment this value for each new EnumJobs call for a given printerName
An index of -1 will return the status of the printer, rather than a particular job.
jobName(Object) obtains a name for the job (available as jobName[0])

Return Value

Returns a numeric value indicating the current status of the job. The bits have the following meaning:

MeaningValue
JOB_STATUS_PAUSED0x00000001
JOB_STATUS_ERROR0x00000002
JOB_STATUS_DELETING0x00000004
JOB_STATUS_SPOOLING0x00000008
JOB_STATUS_PRINTING0x00000010
JOB_STATUS_OFFLINE0x00000020
JOB_STATUS_PAPEROUT0x00000040
JOB_STATUS_PRINTED0x00000080
JOB_STATUS_DELETED0x00000100
JOB_STATUS_BLOCKED_DEVQ0x00000200
JOB_STATUS_USER_INTERVENTION0x00000400
JOB_STATUS_RESTART0x00000800

Example

<script defer>
function window.onload() {
  for ( i = 0; printer = factory.printing.EnumPrinters(i); i++ ) {
    alert("Printer name: "+printer);
    var job = {};
    for ( j = 0; status = factory.printing.EnumJobs(printer, j, job); j++ )
      alert("Job name: "+job[0]+", status: "+status);
  }
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumPrintersGetJobsCountPrint

EnumPrinters


Description

Enumerates locally-available printers.

Syntax

printerName = printing.EnumPrinters(index)

ParameterDescription
index(Number) Zero-based index of the printer. Increment this value for each new EnumPrinters call

Return Value

Returns the string name of the next printer. An empty value means that enumeration is over.

Example

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<p><small id=idOutput></small>

<script defer>
function OutputHtml(html) {
  idOutput.insertAdjacentHTML("BeforeEnd", html)
  idOutput.scrollIntoView(false)
}

function EnumAll() {
  OutputHtml("Default printer: <b>" + factory.printing.DefaultPrinter() + "</b><br>")
  for ( i = 0; name = factory.printing.EnumPrinters(i); i++ ) {
    OutputHtml("Printer: <b>" + name + "</b><br>Job count: " + factory.printing.GetJobsCount(name) + "<br>")
    var jobName = {}
    for ( j = 0; status = factory.printing.EnumJobs(name, j, jobName); j++ )
      OutputHtml("Job: <b>" + jobName[0]+"</b>Status: " + new Number(status).toString(16) + "<br>")
  }
}

function window.onload() {
  EnumAll()
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumJobsEnumPrintersGetJobsCountPrintPrintSetup

GetJobsCount


Description

Returns the number of printing jobs for the specified printer.

Syntax

numJobs = printing.GetJobsCount(printer)

Return Value

Returns a numeric value.

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumJobsEnumPrintersPrint

GetMarginMeasure


Description

Returns current units of measure for print-out margins, either millimeters or inches. Use SetMarginMeasure to switch the default units.

Syntax

units = printing.GetMarginMeasure()

Return Value

Returns the currently-set units of measure. 1 stands for millimeters, 2 for inches.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthrightMargintemplateURLtopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupPrintPrintPrintSetupSetMarginMeasure

IsSpooling


Description

Checks if spooling is in progress as result of a Print call, or for any downloads outstanding in the queue created by PrintHTML PrintXML orBatchPrintPDF calls.

You can force the blocking wait state with WaitForSpoolingComplete to make sure all downloads are complete and spooling is done at any point in your code.

Syntax

isSpooling = printing.IsSpooling()

Return Value

Returns a boolean value indicating whether or not there are still outstanding unspooled downloads to be printed

Example

The following example closes the window when the spooling is done:

<script defer>

function PrintAllDocs() {
  factory.printing.PrintHTML("info.htm");
  factory.printing.PrintXML(src1);
  factory.printing.PrintXML(src2);
  CheckSpooling();
}

function CheckSpooling() {
  if ( !factory.printing.IsSpooling() ) window.close()
  setTimeout("CheckSpooling()", 1000);
}

</script>

See Also

HTML Printing with ScriptX

onafterprintonbeforeunload

BatchPrintPDFOwnQueuePrintPrintHTMLPrintXMLSleepWaitForSpoolingComplete

IsTemplateSupportedbasic


Description

Checks whether or not Print Templates are supported on the end user's system (i.e. checks for Internet Explorer 5.5 or later).

Syntax

isTemplateSupported = printing.IsTemplateSupported()

Return Value

Returns a boolean value indicating whether or not Print Templates are supported.

Applies To

printing

See Also

HTML Printing with ScriptX

templateURL

PreviewPrintPrintHTML

OwnQueue


Description

OwnQueue is used to organize a detached printing queue. Use this method to queue all PrintHTML calls in a separate process. The process is disconnected from the current session (cookies, SSL context, etc) but the calling window can be closed at any time without waiting for spooling to compete. 

OwnQueue should be called before any PrintHTML or PrintXML commands to take effect.

Syntax

printing.OwnQueue()

Applies To

printing

See Also

PrintHTMLPrintXML

PageSetupbasic


Description

Invokes the standard Internet Explorer Page Setup... dialog. If the user closes the dialog with the OK button, current settings will be updated and anonpagesetup event will be fired. 

The PageSetup method is part of the basic freely-distributable printing subset.

Syntax

result = printing.PageSetup()

Return Value

Returns a boolean value indicating whether or not a user has closed the dialog with the OK button.

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMargindisableUIfooterheaderleftMarginonpagesetuponuserpagesetuppaperSizepaperSourceportraitrightMargintopMargin

PrintPrintHTMLPrintSetup

Pause


Description

Pauses either the entire print queue or an individual job. In order to pause a print queue the user must possess administration rights on the printer, jobs belonging to the user may be paused.

Syntax

o.Pause()

Applies To

printerControlJob

See Also

Resume

Previewbasic


Description

Invokes the Print Preview... pane in Internet Explorer 5.5 and later.

The Preview method is part of the basic freely-distributable printing subset.

Syntax

printing.Preview(oFrame)

ParameterDescription
oFrame[Optional] HTML frame to preview. By default, the top-level containing page will be previewed (i.e. the whole browser window content).

The use of this parameter is not part of the basic subset, a license is required. Without a license, default behaviour (preview the whole window) will occur.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

onuserprintpreviewtemplateURL

IsTemplateSupportedPrint

Printbasic


Description

Prints the contents of the specified window or frame using the current printing settings. Please note these important changes regarding printing without a prompt.

This method is part of the basic freely-distributable printing subset.

However, the acquisition of a MeadCo Publishing License means that you can customize various printing properties such as copiesduplexpaperSize,printBackground etc., target specific printer or print externally-located documents with PrintHTML. See HTML Printing with ScriptX for more info. 

Syntax

printing.Print([prompt[, frameOrWindow]])

ParameterDescription
prompt(Bool) whether or not to prompt
frameOrWindow(Object) optional HTML frame or window횂쨩 to print. By default, the containing page (that hosts the ScriptX object) will be printed

Return Value

Returns false if printing with a prompt and the user cancels the printing.

Example

Check out the source code of the ScriptX BasicAdvanced and Techie printing examples.

The following simple but complete example shows how to print the containing page:

<head>
<title>MeadCo's ScriptX: Print</title>
<!-- special style sheet for printing -->
<style media="print">
.noprint { display: none }
</style>
</head>

<body scroll="auto">

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  factory.printing.header = "MeadCo's ScriptX: Print"
  factory.printing.footer = "The de facto standard for advanced web-based printing"
  factory.printing.portrait = false
  idPrint.disabled = false; // enable UI button
}

function Print() {
  factory.printing.Print(false); // no prompt
}
</script>

<p>Hello, world!</p>

<div class=noprint>
<hr>The button itself will not be printed:
<input id=idPrint disabled type="button" value="Print w/o prompt" onclick="Print()">
</div>

</body>

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

DefaultPrinterEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueuePageSetupPreviewPrint,PrintHTMLPrintPDFPrintSetupPrintXMLSetMarginMeasureSetPageRange,, WaitForSpoolingComplete

printDocument  (v6.3.436 and later)


Description

Loads the specified file and sends the content directly to the printer. The file bytes are not rendered in any way, they are sent to the printer for the printer to interpret. In this way, postscript can be sent directly to the printer or label printing commands.

This method is synchronous; it will not return until the file load and print is complete.

Syntax

rawPrinting.printDocument(url)

ParameterDescription
url(String) url of the file whose contents are to be sent to the printer. The url must be absolute but may refer to local (file://) resources.

Return Value

none.

Applies To

rawPrinting

Examples

The following simple but complete example shows how to print a label stored on the web server to a Zebra printer. The sample is assuming that some process has run on the server to generate and store the required label.

<head>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>

function printLabel() {
  var p = factory.rawPrinting;

  // select the Zebra printer
  p.printer = "Zebra  LP2844-Z"

  // must give the full url of the file...
  // The printDocument method is synchronous
  p.printDocument(factory.baseURL("label.txt"));

}
</script>


</head>

See Also

printString

PrintHTML


Description

Prints either specified HTML text or the HTML or XML document specified by the URL using the current printing settings in the same session context. The method is asynchronous. It returns before the document is downloaded and printed.

Important note:

The html to be printed must not be 'ScriptX-enabled' - it must not contain an object tag referencing the ScriptX object nor script code that uses that object. Attempting to print html (either specified html text or document specified by url) that contains the ScriptX object can lead to strange errors and failure of the entire printing process, including causing Internet Explorer to stop responding.

PrintHTML may be used to organize a printing queue in a separate process, in which case the current window may be closed without waiting for pending downloads to complete. See OwnQueue for more details.

Syntax

printing.PrintHTML(url[, prompt = false])

ParameterDescription
url(String) URL/html text to print:
ProtocolPrints
html://The html is loaded and printed, e.g. html://<html><head><title>Dynamic Printing</title></head><body>Hello world!</body></html>
any other, e.g. http://, https:// or if no protocol specified.The document is downloaded and printed. A relative (to the current page) url may be given.

Note: The target document at 'url' must NOT be 'ScriptX-enabled'.
prompt(Bool) Specifies whether or not the user should be prompted before the download is queued

Return Value

Returns false if printing with a prompt and the user cancels the printing.

Applies To

printing

Examples

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

The following simple but complete example shows how to print an externally-located document:

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  idPrint.disabled = false;
}

function PrintHTML(url) {
  factory.printing.PrintHTML(url);
}
</script>

<input id=idPrint disabled type="button" value="PrintHTML('info.htm')"
 onclick="PrintHTML('info.htm')">

</body>

The following example illustrates dynamic creation of the HTML to be printed:

 <!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script>
function doPrintDemo() {

	var n;
	var str = "<html><head>";
	str += "<link rel='stylesheet' type='text/css' href='/zeepe/resources/zp_content.css' />";
	str += "<title>ScriptX Dynamic Reports</title></head><body>";

	for (n=0; n<10; n++) {
		str += "<p>Dynamically created line number: " + (n+1) + "</p>";
	}

	str += "<hr/><p>Note that style sheets, scripts, images etc must be referenced by their full url</p>");
	str += "</body></html>";

	factory.printing.header = "ScriptX Dynamic Printing";
	factory.printing.footer = "";
	factory.printing.printHTML("html://"+str);
}
</script>

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

BatchPrintPDFIsSpoolingOwnQueuePageSetupPrintPrintSetupPrintXMLWaitForSpoolingComplete

PrintPDF (ScriptX Corporate 32 bit Edition)


Description

Downloads and prints a PDF document - the method will not return until the download and print has completed.

For greater control over printing, such as being able to select paper size and source and the printer to use and for a responsive experience for the user, please see the BatchPrintPDF method.

This updated functionality now requires v6.6 or later of ScriptX Corporate 32-bit Edition and an Enhanced PDF Printing license.

Please contact MeadCo sales for details.

Syntax

printing.PrintPDF(PDF[, prompt = true[, shrinkToFit = true [, from = -1[, to = -1]]]);

ParameterDescription
PDFAnonymous javascript object with the member value url containing the location of the document to be printed, as illustrated below.
prompt(Bool) Indicates whether or not to prompt the user before printing
shrinkToFit(Bool) Shrink the PDF page to fit the paper, optional, true by default
from(Number) Print from the specified page, optional, all pages by default
to(Number) Print to the specified page, optional, all pages by default

Example

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function PrintPDF() {
  factory.printing.PrintPDF({ url: "example.pdf" });
}
</script>

<input id=idPrint type="button" value="Print the PDF"
 onclick="PrintPDF()">

</body>

Applies To

printing

See Also

HTML Printing with ScriptX

BatchPrintPDFPrintPrintHTML

PrintSetup


Description

Invokes the standard Windows Print Setup... dialog, thus allowing a user to modify current print settings. If the user closes the dialog with the OK button, current settings will be updated and an onpagesetup event will be fired. No printing will occur in either case. 

Syntax

result = printing.PrintSetup()

Return Value

Returns a boolean value indicating whether or not the user has closed the dialog with the OK button.

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

Applies To

printing

See Also

HTML Printing with ScriptX

collatecopiesdisableUIduplexprinterprintToFileName

DefaultPrinterPageSetupPrintPrintHTML

printString


Description

Sends the specified text directly to the printer. The string is not rendered in any way, its is sent to the printer for the printer to interpret. In this way, label printing commands or (say) postscript can be sent directly to the printer.

This method is synchronous; it will not return until the print is complete.

Syntax

rawPrinting.printString(sText)

ParameterDescription
sText(String) text to print. The string is converted from Unicode to an ANSI string (bytes) and sent as-is to the printer.

Return Value

none.

Applies To

rawPrinting

Examples

The following simple but complete example shows how to print a label to a Zebra printer:

<head>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>

function printLabel() {
  var p = factory.rawPrinting;

  p.printer = "Zebra  LP2844-Z"
  p.printString("^XA^FO50,50^ADN,36,20,^FDScriptX RawPrinting^FS^FO50,100^ADN,36,20,^FDMead & Company^FS^XZ");

}
</script>


</head>

See Also

printDocument

PrintXML


Description

This method is an alias for PrintHTML, preserved for compatibility reasons. You can print both XML (XSL-processed) and HTML files with PrintHTML. See the PrintHTML method description for more info.

Example

The following simple but complete example shows how to print an externally-located XML document:

<head>
<title>MeadCo's ScriptX: PrintXML</title>
<!-- special style sheet for printing -->
<style media="print">
.noprint     { display: none }
</style>
</head>

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  idPrint.disabled = false;
}

function Print() {
  // set footer
  factory.printing.footer = "Printed with MeadCo's ScriptX";

  // print this page
  factory.printing.Print(false);

  // print linked pages
  var links = idLinks.all.tags("A");
  for ( i = 0; i < links.length; i++ )
    factory.printing.PrintXML(links[i].href)
}
</script>

<p><input id=idPrint class=noprint disabled type="button" value="Print the page and links"
 onclick="Print()">

<p>XML links:
<span id=idLinks>
<a href="info1.xml">Info 1</a>
<a href="info2.xml">Info 2</a>
<a href="info3.xml">Info 3</a>
</span>

</body>

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

BatchPrintPDFIsSpoolingOwnQueuePageSetupPrintPrintHTMLPrintSetupWaitForSpoolingComplete

Purge


Description

Purges all pending print jobs in the queue for the printer. The user must posses administration rights on the printer.

Syntax

o.Purge()

Applies To

printerControl

See Also

Pause

Restart


Description

Restarts the print job - the job must belong to the user or the user must possess administration rights on the printer.

Syntax

job.Restart()

Applies To

Job

See Also

Pause

Resume


Description

Resumes either the entire print queue or an individual job. In order to resume a paused print queue the user must possess administration rights on the printer, paused jobs belonging to the user may be resumed.

Syntax

o.Resume()

Applies To

printerControlJob

See Also

Pause

SetMarginMeasure


Description

Sets the units of measure for print-out margins.

Syntax

printing.SetMarginMeasure(units)

ParameterDescription
units(Number) 1 stands for millimeters, 2 for inches.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizerightMargintopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

GetMarginMeasurePageSetupPrintPrintPrintSetup

SetPageRange


Description

Sets the page selection to print.

It is not possible to know in advance the exact number of pages which will be printed unless you're using a custom Print Template (Internet Explorer 5.5 or later). MeadCo's MaxiPT횂쨩 custom Print Template allows you to specify arbitrary page ranges, as well as only odd, even or both odd and even pages with different margin and header/footer settings. 

Syntax

printing.SetPageRange(selectionOnly[, fromto])

ParameterDescription
selectionOnlyif true, prints the highlighted selection only (if there is one) and from and to are ignored.
If there is no selection, all pages are printed.
fromThe (1-based) page number to start printing from - use 0 to signify all pages should be printed. Only used if selectionOnly is false.
toThe (1-based) page number to print to, used only if selectionOnly is false and from is >= 1

Default behaviour is SetPageRange(false,0)

Applies To

printing

SSee Also

HTML Printing with ScriptX

collatecopiesduplex

PageSetupPreviewPrintPrintSetup

SetPrintScale (v6.3.435 and later)


Description

Use this method to specify the scale to be used during printing - this is print scalingnot view zooming.

The IE 7 style template is required for this method to have any effect.

Syntax

printing.SetPrintScale(lScale,)

ParameterDescription
lScale

(Number) The print scale to use, expressed as a percentage. The value must be either -1 or between 30 and 999 or it will be ignored.

The special value -1 denotes 'scale to fit' where, if necessary, the content is scaled to fit the width of the paper - if scaling is not necessary to fit, 100% scaling is used.

Applies To

printing

Example

function startPreview() {
	var s = document.getElementById("selectScale");
	factory.printing.SetPrintScale(s.options[s.selectedIndex].value);
}

  

See Also

SetPreviewZoomtemplateUrl

 

SetPreviewZoom (v6.3.435 and later)


Description

Use this method to specify the Zoom to be used during print preview - this is view zooming, not print scaling.

Syntax

printing.SetPreviewZoom(lZoom,,pagesX,pagesY)

ParameterDescription
lZoom(Number) The Zoom scaling to use, either expressed as a percentage (e.g. 200 for double full size) or one of the following special values:
-1Zoom to show the full page width in the view.
-2Zoom to show the full page height in the view.
-3Zoom to show 2 full height pages in the view.
0Zoom to show full height pages, layed out as described by the pagesX and pagesY parameters (requires the IE 7 style template).
For the IE 6 and earlier style template, the default value is 75%. For IE 7 and later style template, the default value is -2.
pagesX (optional, requires the IE 7 style template)(Number) Only used with the IE 7 style template when lZoom is 0. Specifies the number of pages to display across the view (columns).
pagesY (optional, requires the IE 7 style template)(Number) Only used with the IE 7 style template when lZoom is 0. Specifies the number of rows of pages to display.

Applies To

printing

Example

function startPreview() {
	var z,x=0,y=0;

	if ( document.getElementById("selectTemplate").selectedIndex != 1 ) { // if not IE 7 template
		var s = document.getElementById("selectZoom");
		z = s.options[s.selectedIndex].value;
	}
	else {
		var s = document.getElementById("selectZoom");
		var s1 = document.getElementById("selectPages");

		var o = parseInt(s1.options[s1.selectedIndex].value);

		switch (o) {
			case 0: // zoomed one page
				z = s.options[s.selectedIndex].value;
				break;

			case 2: // the rest are multi-page views.
				z = 0;
				x = 2;
				y = 1;
				break;

			case 3:
				z = 0;
				x = 3;
				y = 1;
				break;

			case 6:
				z = 0;
				x = 3;
				y = 2;
				break;

			case 12:
				z = 0;
				x = 4;
				y = 3;
				break;

		}
	}

	factory.printing.SetPreviewZoom(z,x,y);
	factory.printing.Preview();
}

  

See Also

SetPrintScale

Sleep


Description

Suspends (sleeps) script execution for a specified timeout or until a passed callback function returns true. This is an efficient way to wait for an event without burning CPU cycles.

Syntax

printing.Sleep(timeout, [callback])

ParameterDescription
timeout(Number) the timeout in milliseconds.
callback(Function) the optional pointer to the function to be periodically called within the Sleep method.
When the function returns true, the sleep is canceled.

Return Value

Returns true if the sleep was canceled by a callback function.

Applies To

printing

Example

The following code snippet navigates a frame to a file then prints its content:

<script defer>
function NavigatePrintFrame(url) {
  idFrame.navigate(url);
  factory.printing.Sleep(100) // let the navigation start
  factory.printing.Sleep(1000*60, IsReady) // sleep for 1 minute or until the document is ready
  factory.printing.Print(true, idFrame)
}
function IsReady() {
  return idFrame.document.readyState == "complete"
}
</script>

See Also

HTML Printing with ScriptX

onafterprint

IsSpoolingPrintWaitForSpoolingComplete

WaitForSpoolingComplete


Description

Waits for all pending download and spooling operations originated with PrintPrintHTML/PrintXML and BatchPrintPDF calls to complete.WaitForSpoolingComplete provides visual feedback such as a modal window state and an hourglass cursor.

Syntax

printing.WaitForSpoolingComplete()

Return Value

Returns a boolean value indicating whether or not there are still outstanding unspooled downloads to be printed.

Example

Check out the source code of the ScriptX Techie Printing example.

<script defer>
function PrintAndGo() {
  if ( factory.printing.Print() )
    factory.printing.WaitForSpoolingComplete()
  window.close()
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

onafterprintonbeforeunload

BatchPrintPDFIsSpoolingOwnQueuePrintPrintHTML,  Sleep


MeadCo's ScriptX, MaxiPT and the MeadCo Security Manager are Copyright (c) Mead & Co Limited, 1998-2008.

Microsoft, Windows, Internet Explorer are registered trademarks of Microsoft Corporation. All companies and product names mentioned are trademarks of the respective companies.

MeadCo ScriptX Control

Posted by 1010
02.Oracle2012. 3. 26. 16:13
반응형

SELECT
        CASE
                WHEN    TO_CHAR(MAX(ntfc_no) + 1) > '99999999'
                THEN '00000001'
                ELSE    LPAD(MAX(TO_NUMBER(REGEXP_REPLACE(ntfc_no, '[^0-9]'))) + 1, 8, '0')
        END AS ntfc_no
  FROM  TA_ICL_NTFC_DTL
Posted by 1010
02.Oracle/DataBase2012. 3. 26. 11:01
반응형

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
WITH t(type, name, code) AS
(
SELECT '과일', '사과', '0' FROM dual
UNION ALL SELECT '과일', '레몬', '1' FROM dual
UNION ALL SELECT '과일', '포도', '2' FROM dual
UNION ALL SELECT '과일', '참외', '3' FROM dual
UNION ALL SELECT '채소', '오이', '0' FROM dual
UNION ALL SELECT '채소', '당근', '1' FROM dual
UNION ALL SELECT '채소', '호박', '2' FROM dual
)
SELECT type
, SUBSTR(XMLAgg(XMLElement(x, ',', name) ORDER BY code).Extract('//text()'), 2) name_9i
, wm_concat(name) name_10g
, ListAgg(name, ',') WITHIN GROUP(ORDER BY code) name_11g
FROM t
GROUP BY type
ORDER BY type
;

<실행 결과>
TYPE NAME_AGG
과일 사과,레몬,포도,참외
채소 오이,당근,호박


출처 : http://www.oracleclub.com/article/55512
Posted by 1010
02.Oracle/DataBase2012. 3. 16. 11:29
반응형

집합 쿼리(UNION, INTERSECT, MINUS)

집합 연산자를 사용시 집합을 구성할 컬럼의 데이터 타입이 동일해야 한다.

  • - UNION : 합집합
  • - UNION ALL : 중복 데이터를 다 포함하는 합집합
  • - INTERSECT : 교집합
  • - MINUS : 차집합

UNION

UNION은 두 테이블의 결합을 나타내며, 결합시키는 두 테이블의 중복되지 않은 값들을 반환 한다.

 
SQL> SELECT deptno FROM emp
     UNION
     SELECT deptno FROM dept;
 
    DEPTNO
----------
        10
        20
        30
        40
    

UNION ALL

UNION과 같으나 두 테이블의 중복되는 값 까지 반환 한다.

 
SQL> SELECT deptno FROM emp
     UNION ALL
     SELECT deptno FROM dept;
 
   DEPTNO
---------
       20
       30
       30
       20
       30
       30
       10
       20
       10
       30
    

INTERSECT

INTERSECT는 두 행의 집합중 공통된 행을 반환 한다.

 
SQL> SELECT deptno FROM emp
     INTERSECT
     SELECT deptno FROM dept;
    
    DEPTNO
----------
        10
        20
        30
    

MINUS

MINUS는 첫 번째 SELECT문에 의해 반환되는 행 중에서 두 번째 SELECT문에 의해 반환되는 행에 존재하지 않는 행들을 반환 한다.

 
SQL> SELECT deptno FROM dept
     MINUS
     SELECT deptno FROM emp;
 
    DEPTNO
----------
        40
    

문서에 대하여

  • - 작성자 : 김정식 (oramaster _at_ naver.com)
  • - 작성일 : 2002년 08월 30일
  • - 강좌 URL : http://www.oracleclub.com/lecture/1507
  • - 이 문서를 다른 블로그나 홈페이지에 게재하실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^
  • - 오라클클럽의 모든 강좌는 크리에이티브 커먼즈의 저작자표시-비영리-동일조건변경허락(BY-NC-SA) 라이선스에 따라 자유롭게 사용할 수 있습니다.
Posted by 1010
반응형

팝업창을 닫으려고 window.close 와 self.close 를 사용하니..

창을 닫겠습니까?! 라는 경고창이 뜬다.. ㅠㅠ

사용자 왈.. 이거 안보이게 해줄수 있나요?! 흠....

겁나 검색 해보니.. 나왔다... 퍼옴...

window.open('','').close(); 이걸로 해결 했심둥...ㅋㅋ

이유는 IE 보안정책?!!!

6버전?!(아직 쓰시는분 있나?!) 과 7버전 이상의 보안정책 다르다네..

- 해결방법
IE6버전은 window.close(); 사용해도 됨(안되면 어쩔수 없구..ㅠㅠ).
IE7버전 이상은 window.open('','').close(); 이걸로...ㅎㅎ


출처 : http://jjun7983.tistory.com/141#comment10522579
Posted by 1010
98..Etc/Etc...2012. 3. 15. 11:01
반응형

ERwin을 재설치하는 경우 특정파일(mmopn32.exe)에서 에러가 발생하면서 실행이 되지 않는다.
제네시스 사이트에서 확인한 바에 따르면 프로그램의 빌드차이와 같은 이유로 발생한다고 한다.
번거롭더라도 앞서 설치되었던 ERwin에 대한 정보를 모두 제거한 후에 다시 설치하여야 한다.
1. 프로그램을 삭제한다.

[제어판 > 프로그램 추가/제거]

2. 해당 폴더를 삭제한다.
[Program Files > CA]
[Program Files > CA_LIC]
- CA_LIC 폴더가 특정 파일의 공유 및 사용으로 삭제가 되지 않는 경우 해당 파일을 사용하는 프로세스를

종료한다. [작업관리자 > 프로세스 > LogWatNT.exe]
3.관련 파일을 삭제한다.
시스템폴더(Windows)에 있는 Erwin*.*, RTBPreferences.pref, SCAPI.ini
4. 서비스를 종료한다.
제어판 > 관리도구 > 서비스 > CA_LIC*
5. 레지스트리를 정리한다.
검색을 통해서 관련 키워드로 설정된 값을 삭제한다.
Erwin, AllFusion, CA_LIC
6. 리부팅한다.
cf.
ca.com에서 평가판을 직접 다운받았을 경우 하나의 평가판 프로그램을 중복해서 사용할 수 없다.
평가판 자체도 라이센스 키를 가지므로 평가기간 만료후에는 새로운 평가판을 다운로드하여 설치하여야 할 것 같다.(실제로 적용해 보지는 않았다.)


출처: http://skql.tistory.com/492

Posted by 1010
54.iBATIS, MyBatis2012. 3. 13. 09:33
반응형

///// 기본환경 정보 /////////////////////////////

1. iBatis 2.3.4

2. JSP3.0

3. Tomcat 7.0

4. Oracle 10g HR 계정의 sample table



///// 예제 따라하기 ////////////////////////

첨부된 war파일을 import 하시거나 압축을 해제한 후

아래의 순서대로 따라하시면 됩니다 ^^


1. log4j.properties src폴더에 복사한다.

2. db.properties 생성하여 SqlMapConfig.xml에서 이용할 설정 정보를 입력한다.

3. SqlMapConfig.xml에 전체옵션 및 트랜잭션 메니저를 설정한다.

4. Day1.xml 사용될 쿼리를 매핑한다.

5. log4j 사용을 위한 LogLoader.java 파일을 생성한다.

6. SqlMapConfig.xml파일을 로딩할 IBatisSettingLoader.java 파일을 생성한다.

7. 검색결과를 관리해주는 IBatisManager.java 파일을 생성한다.

8. Day1Dao.java 파일을 생성한다.

9. day1.jsp를 생성 후 Day1Dao.java 객체를 생성하여 샘플데이터를 출력한다.

샘플데이터 리스트는 jstl을 이용하여 출력한다.




///// 소스구조 및 결과화면 /////////////////













///////////////////////////////////////////////////////////////////////////////

1. log4j.properties src폴더에 복사한다.

log4j 설정은 패스~~ 첨부파일을 참조하시고....



///////////////////////////////////////////////////////////////////////////////

2. db.properties 생성하여 SqlMapConfig.xml에서 이용할 설정 정보를 입력한다.


driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@127.0.0.1:1521:ORCL
user = hr
pwd = hr



///////////////////////////////////////////////////////////////////////////////

3. SqlMapConfig.xml에 전체옵션 및 트랜잭션 메니저를 설정한다.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>

<!-- properties파일 경로 설정 -->
<properties resource="db.properties" />

<!-- 전체 옵션의 설절 -->
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxTransactions="8"
maxSessions="64"
maxRequests="128"
useStatementNamespaces="true"
/>

<typeAlias type="common.value.DataMap" alias="dmap" />

<typeHandler callback="com.ibatis.sqlmap.engine.type.SqlTimestampTypeHandler"
javaType="java.util.Date" />

<!-- 트랜잭션 매니저 설정 -->
<transactionManager type="JDBC" commitRequired="true">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}" />
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${user}"/>
<property name="JDBC.Password" value="${pwd}"/>
</dataSource>
</transactionManager>

<sqlMap resource="query/exam/Day1.xml" /> <!-- 예제1 -->

</sqlMapConfig>




///////////////////////////////////////////////////////////////////////////////

4. Day1.xml 사용될 쿼리를 매핑한다.


동적인 where절의 생성

파라미터로 넘어온 맵의 키값중 job_id 가 존재하면 where조건절을 생성하고

그렇지 않으면 무시한다.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="query.exam.Day1">

<!-- JOBS 테이블의 모든 로우정보를 받아옴 -->
<select id="getJobs" resultClass="java.util.HashMap">
SELECT * FROM JOBS
<dynamic prepend="where">
<isNotNull property="job_id">
JOB_ID = #job_id#
</isNotNull>
</dynamic>
</select>

</sqlMap>



///////////////////////////////////////////////////////////////////////////////

5. log4j 사용을 위한 LogLoader.java 파일을 생성한다.



///////////////////////////////////////////////////////////////////////////////

6. SqlMapConfig.xml파일을 로딩할 IBatisSettingLoader.java 파일을 생성한다.


///////////////////////////////////////////////////////////////////////////////

7. 검색결과를 관리해주는 IBatisManager.java 파일을 생성한다.


package common.db;

import java.util.ArrayList;
import java.util.HashMap;
import com.ibatis.sqlmap.client.SqlMapClient;
import common.util.LogLoader;

/**
* iBatis 컨트롤 메니저
* @author 조한중(hanjoongcho@gmail.com)
* @version 1.0
*/
public class IBatisManager {

SqlMapClient sqlMap;

public IBatisManager() {
sqlMap = IBatisSettingLoader.getSqlMapClient();
}


/**
* HashMap 형태의 파라미터를 받아 리스트를 반환함
* @param queryMap
* @param param
* @return
*/
public ArrayList<HashMap<String, String>> selectList(String queryMap,HashMap<String,

String> param){
ArrayList<HashMap<String, String>> returnlist = new ArrayList<HashMap<String,

String>>();
try{
//쿼리맵을 출력한다
LogLoader.getLogger().info("\n[SELECT_LIST : "+queryMap+"]");
//쿼리시작 시간
long startTime = System.currentTimeMillis();
ArrayList list;
if(param==null){
list = (ArrayList)sqlMap.queryForList(queryMap);
}else{
list = (ArrayList)sqlMap.queryForList(queryMap, param);
}
//쿼리 리턴시간
LogLoader.getLogger().info("\n 수행시간 : " +(System.currentTimeMillis()-startTime) +"

ms ");
LogLoader.getLogger().info("\n 선택된 로우의 수 : " +list.size());
if(list!=null){
int size = list.size();
for(int i=0;i<size;i++){
returnlist.add((HashMap)list.get(i));
}
}
}catch (Exception e){
LogLoader.getLogger().error(e.toString());
}
return returnlist;
}


}


///////////////////////////////////////////////////////////////////////////////

8. Day1Dao.java 파일을 생성한다.


///////////////////////////////////////////////////////////////////////////////

9. day1.jsp를 생성 후 Day1Dao.java 객체를 생성하여 샘플데이터를 출력한다.

샘플데이터 리스트는 jstl을 이용하여 출력한다.



<%@page import="common.util.StringUtil"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="exam.day1.dao.Day1Dao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%


String job_id = StringUtil.nullToEmpty(request.getParameter("job_id"));
Day1Dao dao = new Day1Dao();
ArrayList<HashMap<String, String>> list = null;
ArrayList<HashMap<String, String>> jobIdList = dao.getJobId(); //선택옵션 생성
if("".equals(job_id)){ //검색 키워드가 없을경우
list = dao.getJobs(null);
}else{ //검색 키워드가 있을경우
HashMap<String,String> map = new HashMap<String,String>();
map.put("job_id",job_id);
list = dao.getJobs(map);

}
%>
<c:set var="job_id" value="<%=job_id%>"></c:set>
<!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>DAY - 1</title>
<script type="text/javascript">
function searchGo() {
var job_id = document.getElementById('job_id').value;
location.href = 'day1.jsp?job_id=' + job_id;
}
</script>
</head>
<body>

<div>
<select onchange="searchGo();" id="job_id" name="job_id">
<option value="">전체조회</option>
<c:forEach var="jobIdList" items="<%=jobIdList%>">
<option value="${jobIdList.JOB_ID}" <c:if test = "${jobIdList.JOB_ID == job_id}"> selected="selected" </c:if> >${jobIdList.JOB_ID}</option>
</c:forEach>
</select>
기본 동적쿼리[셀렉트박스를 선택해서 파라미터가 있으면 where 조건절을 생성함]
<table border="1">
<colgroup>
<col width="20%">
<col width="40%">
<col width="20%">
<col width="20%">
</colgroup>

<thead>
<tr>
<th>JOB_ID</th><th>JOB_TITLE</th><th>MIN_SALARY</th><th>MAX_SALARY</th>
</tr>
</thead>

<tbody>
<!-- jstl을 이용하여 list에 담겨있는 Map의 value값을 호출 -->
<c:forEach var="list" items="<%=list%>">
<tr>
<td>${list.JOB_ID}</td>
<td>${list.JOB_TITLE}</td>
<td>${list.MIN_SALARY}</td>
<td>${list.MAX_SALARY}</td>
</tr>

</c:forEach>
</tbody>
</table>
</div>

</body>
</html>
Posted by 1010
98..Etc/node.js2012. 3. 12. 16:46
반응형
이틀간의 삽질을 기념하며 한 번 정리해봅니다.

node.js 설치 정리..

nodejs.org에 들어가서 windows버전의 msi설치파일을 다운로드 받는다.

해당 파일을 설치한다. (설치경로는 default로 c:\Program Files\nodejs\ 이다.)

cmd창을 열어 c:\Program Files\nodejs\ 경로로 이동후 다음을 실행
npm install express 엔터

C:\Program Files\nodejs\node_modules\express 경로에 express가 설치되었고
C:\Program Files\nodejs\node_modules\.bin 경로에 express.cmd 실행파일이 생성되었다.

C:\Program Files\nodejs\node_modules\.bin 경로로 이동 후
express create /nodeExpressSite 엔터

C:\nodeExpressSite 경로에 express용 사이트가 하나 생성되었다.

C:\nodeExpressSite 이동후 다음의 명령실행
node app.js
에러가 난다(필요한 모듈이 없어서..)

C:\nodeExpressSite 디렉토리에 들어가서 다음의 명령 실행
npm install -d

C:\nodeExpressSite 디렉토리에 필요한 모듈들이 자동으로 설치된다.

다시 다음의 명령 실행
node app.js
3000포트에 개발모드로 서버가 리스닝 하고 있다는 메시지가 나온다.

브라우저를 열어서 http://localhost:3000 로 접속해본다.
Welcome to Express라는 메시지가 뜬다.

이제부터 express 공부시작.. 화이팅~

도움을 받은 곳
kenu형의 동영상강좌
https://github.com/visionmedia/express 설명
http://firejune.io/express/ firejune님의 express번역사이트



출처 : http://okjsp.pe.kr/seq/184404
Posted by 1010
98..Etc/node.js2012. 3. 12. 16:24
반응형

이 포스팅은 node.js는 무엇인가? #1에 이어진 포스팅입니다.



Hello World에 대한 예제는 여러가지가 있지만 아무래도 node.js를 만든 Ryan Dahl가 보여준 예제가 node.js를 가장 잘 표현해 주는것 같아서 Ryan Dahl가 JSConf에 사용한 Hello World 예제를 그대로 사용하였습니다. nettuse+의 Learning Server-Side JavaScript with Node.js 에 나온 소스도 참고하시면 도움이 될 듯 합니다.



Node.js 설치하기
Node.js는 Mac OS X, Linux, FreeBSD같은 Unix기반의 시스템에서만 구동됩니다. (최근 Windows쪽에서도 할 수잇다느 포스팅을 본적이 있는것 같은데 지금은 찾을 수 없네요.) Node.js v0.6.x부터는 Windows에서도 동작합니다.

node.js를 다운로드 받습니다. node.js 공식사이트에서 최신 릴리즈버전을 다운로드 를 받을 수 있으며 현재 버전은 0.1.97입니다. 다운로드 받은 파일을 원하는 위치에 압축을 풀면 됩니다. Node.js는 GITHUB 에서 저장소를 사용하고 있기 때문에 GIT을 이용해서 git clone http://github.com/ry/node.git 명령어을 사용하면 현재 개발중인 최신소스를 받아서 테스트 해 볼 수 있습니다.

node.js가 소스가 있는 폴더로 이동하여 다음과 같은 명령어를 실행합니다.
./configure
make
sudo make install

설치할때 각 라이브러리를 체크하는데 단순히 현재 시스템에 지원여부를 체크하는 것이므로 not found라고 나와도 문제가 있는 것이 아니므로 신경쓰지 않아도 됩니다. (./configure를 하지 않으면 Project not configured 오류가 발생합니다.)

Node.js를 실행하기 위해서는 Node.js의 node명령어를 사용해야 하기 때문에 환경변수 path에 node.js가 설치된 경로(/Users/Outsider/node 같은)를 추가하면 아무데서나 node명령어를 사용할 수 있습니다.(우분투에서는 sudo gedit /etc/environment로 OSX는 sudo vi /etc/paths를 사용해서 PATH를 수정해 볼 수 있습니다. 수정된 PATH는 재로그인 후에 적용이 되며 env나 echo $PATH를 사용해서 확인할 수 있습니다.) V8은 내장되어 있고 별도의 의존성이 전혀 없기 때문에 설치하고 바로 사용할 수 있습니다.



Hello World 실행하기
아래의 예제들은 Node.js 0.1.96버전을 사용하였습니다. Ryan Dahl가 시연했던 코드와는 API가 변경된 내용이 많기 때문에 아래의 예제들은 0.1.96버전에서 동작하도록 수정하였습니다.
1
2
3
4
5
6
// helloworld1.js
var sys = require("sys")
setTimeout(function() {
sys.puts("world");
}, 2000);
sys.puts("hello");

Hello World 예제입니다.

node helloworld1.js

위의 명령어를 실행하면 node.js가 실행됩니다. Node.js는 더이상 할일이 없으면 자동으로 종료됩니다.

Hello World 실행화면



Hello World 실행하기2
1
2
3
4
5
6
7
8
9
10
puts = require("sys").puts;
setInterval(function() {
puts("hello");
}, 500);
process.addListener("SIGINT", function() {
puts("good-bye");
process.exit(0);
});

Hello World 실행화면

두번째 예제입니다. setIntervla을 이용해서 hello라는 메시지를 0.5초마다 계속 반복적으로 출력해 주고 종료명령인 Ctrl + C를 입력하면 good-bye라는 메시지를 출력한 후에 종료해줍니다. process는 V8 그 자체를 의미합니다. process에 SIGINT라는 이벤트리스너를 추가하여 해당시그널이 왔을때 이벤트가 발생하게 됩니다.



TCP 서버 예제
1
2
3
4
5
6
7
8
9
var tcp = require("net");
var s = tcp.createServer();
s.addListener("connection", function(c) {
c.write("hello!");
c.end();
});
s.listen(8000);

TCP 서버 예제입니다. 1번라인의 tcp는 현재 버전에서 net으로 변경되었으며 5번라인의 send()는 write()로, 6번라인의 close()는 end()로 변경되었기 때문에 현재 버전에 맞게 수정되었습니다.

TCP 서버 실행화면

위 화면에서 뒷쪽의 터미널에서 TCP서버를 실행시켜두고 터미널을 새로 띄워서 localhost에 TCP서버에 접속한 것입니다. 작성해 놓은대로 hello!를 출력한 뒤에 접속을 종료합니다. 9번 라인에서 TCP서버는 8000포트를 이용하도록 설정되어 있습니다. net객체는 접속이 들어올때마다 connection이벤트를 발생시키며 HTTP 업로드가 될때 각 패킷마다 body 이벤트가 호출됩니다.

사용자 삽입 이미지

아직 완전히 API가 Fix되지 않았기 때문에 버전에 따라서 변경되는 내용들이 있는 상황입니다. 일일이 다 테스트 해 본것은 아니지만 버전에 따라 변경되는 내용이 존재하고 있고 바로바로 문서에 반영되는 것은 아니기 때문에 상황에 따라서는 소스를 직접 열어보아야 하는 상황입니다만 위의 화면처럼 현재버전의 require("sys")대신 구버전에서 사용하던 require("tcp")를 사용할 경우 'tcp'가 'net'으로 변경되었다고 친절하게 알려줍니다.

connection리스너는 createServer의 첫번째 아규먼트로 사용할 수 있기 때문에 위의 코드는 아래처럼 변경할 수 있습니다.
1
2
3
4
5
6
var tcp = require("net");
tcp.createServer(function(c) {
c.write("hello!\n");
c.end();
}).listen(8000);




Simple HTTP 서버 예제
1
2
3
4
5
6
7
8
var http = require("http");
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Hello\r\n");
res.write("World\r\n");
res.end();
}).listen(8080);


Simple HTTP서버 실행화면

웹브라우저에서 접속하면 서버에서 작성한대로 Hello world가 정상적으로 출력됩니다.



스트리밍 서버 예제
1
2
3
4
5
6
7
8
9
10
11
12
var http = require("http");
http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Hel");
res.write("lo\r\n");
setTimeout(function() {
res.write("World\r\n");
res.end();
}, 2000);
}).listen(8000);


스트리밍서버 실행화면

웹브라우저에서는 스트림을 비동기로 받아지지 않아서 curl 을 사용해서 테스트하였습니다. 접속하면 Hello가 바로 찍힌뒤 setTimeout으로 설정한대로 2초뒤에 World가 출력되고 접속이 종료됩니다.



node.js의 시스템 접근 예제
1
2
3
4
5
6
7
8
var sys = require("sys"),
spawn = require("child_process").spawn;
var ls = spawn("ls", ["-ls", "/"]);
ls.stdout.addListener("data", function(data) {
sys.print(data);
});

사용자 삽입 이미지

위 예제는 시스템에 접근하는 예제입니다. ls -ls /을 실행하여 그 결과를 출력하여줍니다. Node.js는 앞에서도 언급했든이 버퍼링을 강제하지 않습니다. data를 child process의 STDIO를 통해서 스트림하도록 저레벨의 기능(facility)을 사용합니다. (Simple IPC 예제는 chile process의 방법이 완전히 바뀐것 같은데 어떻게 똑같은 예제를 만들어야 할지 전혀 모르겠더군요. ㅠㅠ)



Epilogue
간단히 헬로월드만 따라해보고는 Node.js를 감히 판단할 수는 없겠지만 Node.js가 보여주는 미래는 놀랍습니다. 이벤트드리븐을 이용해서 서버의 퍼포먼스를 엄청나게 끌어들일 수 있으면 현재 프론트앤드 개발자가 가지고 있는 Javascript 스킬을 그대로 사용해서 자신이 원하는 웹서버를 직접 만들어 낼 수 있습니다. 엔터프라이즈급의 서버까지 만들어 낼 수 있을지는 아직 판단하기 어렵지만 정해진 일정기능의 서버는 아주 간단하게 충분한 퍼포먼스를 가지고 만들어 낼 수 있을 듯 합니다. 현재 버전이 0.2도 가지 않은 상황에서 수많은 모듈들 이 개발되고 있는 것으로 보아도 그 미래가 상당히 기대가 됩니다. 아마 올해 node.js를 많이 만지게 될것 같습니다.


출처 : http://blog.outsider.ne.kr/481
Posted by 1010
98..Etc/node.js2012. 3. 12. 16:21
반응형

'node.js 따라배우기'에 해당되는 글 24건
Posted by 1010