Hibernate 쿼 리 언어 HQL 8 대 요점

41094 단어 Hibernate
Hibernate 는 기능 이 매우 강 한 조회 언어 를 가지 고 있 는데 이런 언어 는 의도 적 으로 SQL 과 매우 비슷 해서 개발 자 들 이 파악 하기에 편리 하 다.그러나 HQL 의 문법 표면 에 현혹 되 지 마 세 요.HQL 은 완전히 대상 을 대상 으로 하 는 것 이 므 로 과정 다 형,계승,관련 등 관계 에 사용 할 수 있 습 니 다.
1 대소 문자 민감 성(케이스 감도)
HQL 에서 사용 하 는 자바 의 클래스 이름과 속성 명 은 대소 문자 가 민감 하고 다른 키 워드 는 대소 문자 가 민감 하지 않 습 니 다.그래서'SELECT'는'sELEct'와 같 고'SELECT'와 같 습 니 다.자바 류 이름 도 아니 고 자바 류 의 속성 이름 도 아니 기 때 문 입 니 다.그러나 자바 류 net.sf.hibenate.eg.FOO 는 net.sf.hibenate.eg.Foo 와 같 지 않 고 foo.barSet 도 foo.BARSET 과 같 지 않다.
이 매 뉴 얼 에서 HQL 의 키 워드 는 모두 소문 자 를 사용 합 니 다.일부 사용자 들 은 HQL 의 키 워드 는 대문자 로 읽 기 쉬 운 것 을 발견 할 수 있 지만,이러한 HQL 을 자바 코드 에 끼 워 넣 으 면 추 해 보 입 니 다.
2from 종문(The from clause)
Hibernate 에서 가장 간단 한 from 검색 은 다음 과 같 습 니 다.

 
   
  1. from eg.Cat 

eg.Cat 류 의 모든 인 스 턴 스 를 간단하게 되 돌려 줍 니 다.
검색 의 다른 부분 에서 Cat 를 참조 해 야 할 수도 있 기 때문에 클래스 에 별명(alias)을 설정 해 야 할 때 가 많 습 니 다.

 
   
  1. from eg.Cat as cat 

키워드 as 는 선택 할 수 있 습 니 다.우 리 는 다음 과 같이 쓸 수 있 습 니 다.

 
   
  1. from eg.Cat cat 

여러 종류 가 나타 나 면'피리 카드 축적'이나 교차 연결 을 되 돌려 줍 니 다.

 
   
  1. from Formula as form, Parameter as param 

HQL 의 별명 은 소문 자로 자바 로 컬 변수의 명명 규범 에 부합 하 는 좋 은 습관 입 니 다.
3 연결 및 연결(Associations and joins)
우 리 는 별명 관련 실체,심지어 join 으로 관련 값 의 집합 요 소 를 사용 합 니 다.

 
   
  1. from eg.Cat as cat  
  2.  
  3.     inner join cat.mate as mate  
  4.  
  5.     left outer join cat.kittens as kitten  
  6.  
  7. from eg.Cat as cat left join cat.mate.kittens as kittens  
  8.  
  9. from Formula form full join form.parameter param  

지원 하 는 연결 형식 은 ANSI SQL 참조:
· inner join
·  left outer join
·  right outer join
·full join(자주 사용 되 지 않 음)
inner join,left outer join 과 right outer join 은 간략하게 쓸 수 있 습 니 다.

 
   
  1. from eg.Cat as cat  
  2.  
  3.     join cat.mate as mate  
  4.  
  5.     left join cat.kittens as kitten  

또한,"fetch"연결 은 부모 대상 과 함께 초기 화 할 수 있 도록 단일 연결 을 사용 하여 연결 하거나 값 의 집합 을 허용 합 니 다.이것 은 Collection 을 사용 하 는 상황 에서 특히 유용 하 다.

 
   
  1. from eg.Cat as cat  
  2.  
  3.     inner join fetch cat.mate  
  4.  
  5.     left join fetch cat.kittens  

fetch join 은 보통 별명 을 설정 할 필요 가 없습니다.연 결 된 대상 은 where 종문 에 사용 되 어 서 는 안 되 고 다른 종문 에 도 사용 할 수 없 기 때 문 입 니 다.
연 결 된 대상 은 검색 결과 에서 직접 돌아 갈 수 없고 부모 대상 을 통 해 접근 할 수 있 습 니 다.
주의:현재 구현 중 검색 에서 하나의 집합 만 되 돌아 갈 수 있 습 니 다.또한 fetch 는 scroll()과 iterator()가 호출 한 조회 에 사용 되 지 않 을 수도 있 습 니 다.마지막 으로 full join fetch 와 right join fetch 는 의미 가 없다 는 점 을 주의해 야 한다.
4 select 종문(The select clause)
select 는 문장 에서 결과 에 집중 적 으로 돌아 오 는 대상 과 속성 을 선택 합 니 다:

 
   
  1. select cat.mate from eg.Cat cat 

위의 이 조 회 는 모든 고양이 의 배우자 에 게 돌아간다.
너 도 elements 함 수 를 사용 하여 집합 요 소 를 되 돌려 줄 수 있다.다음 조 회 는 고양이(Cat)의 모든 고양이(Kitten)를 되 돌려 줍 니 다.

 
   
  1. select elements(cat.kittens) from eg.Cat cat 

검색 도 모든 값 형식(Component 형식의 속성 포함)의 속성 을 되 돌려 줍 니 다.

 
   
  1. select cat.name from eg.DomesticCat cat  
  2.  
  3. where cat.name like 'fri%' 
  4.  
  5. select cust.name.firstName from Customer as cust  

조 회 는 여러 대상 을 되 돌려 줄 수도 있 고 Object[]형식의 배열 의 속성 을 되 돌려 줄 수도 있 습 니 다.

 
   
  1. select mother, offspr, mate.name 
  2.  
  3. from eg.DomesticCat as mother  
  4.  
  5.     inner join mother.mate as mate  
  6.  
  7.     left outer join mother.kittens as offspr  

또는 실제 자바 대상 으로:

 
   
  1. select new Family(mother, mate, offspr)  
  2.  
  3. from eg.DomesticCat as mother  
  4.  
  5.     join mother.mate as mate  
  6.  
  7.     left join mother.kittens as offspr  

위의 이 검색 어 는 Family 류 에 적당 한 구조 함수 가 있다 고 가정 합 니 다.
5 집합 함수(Aggregate functions)
검색 은 속성의 집합 함 수 를 사용 할 수 있 습 니 다:

 
   
  1. select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)  from eg.Cat cat 

select 는 문장의 집합 함수 에서 집합 이 나타 날 수 있 습 니 다.
select cat, count( elements(cat.kittens) )  from eg.Cat cat group by cat
지원 하 는 집합 함수:
· avg(...), sum(...), min(...), max(...)
· count(*)
· count(...), count(distinct ...), count(all...)
distinct 와 all 키워드 의 의 미 는 용법 과 SQL 에서 같 습 니 다.

 
   
  1. select distinct cat.name from eg.Cat cat  
  2.  
  3. select count(distinct cat.name), count(cat) from eg.Cat cat  

6 다 중(polymorphism)
from eg.Cat as cat,Cat 뿐만 아니 라 DomesticCat(집 고양이)같은 하위 클래스 도 있 습 니 다.Hibernate 는 from 에서 문장 에서 자바 류 와 인 터 페 이 스 를 지정 할 수 있 습 니 다.조 회 는 이 클래스 와 이 인 터 페 이 스 를 계승 한 모든 영구적 인 인 인 스 턴 스 를 되 돌려 줍 니 다.다음 조 회 는 모든 오래된 대상 을 되 돌려 줍 니 다:

 
   
  1. from java.lang.Object o 

지정 한 인 터 페 이 스 는 여러 개의 서로 다른 지구 류 에 의 해 실 현 될 수 있 습 니 다.

 
   
  1. from eg.Named n, eg.Named m where n.name = m.name 

마지막 두 개의 조 회 는 1 개의 SQL 을 초과 하 는 select 가 필요 합 니 다.이것 은 문장 에서 지정 한 배열 순서에 따라 전체 결과 집합 을 배열 할 수 없다 는 것 을 의미 합 니 다.이것 은 또한 이 검색 어 를 Query.scroll()로 호출 할 수 없다 는 것 을 의미한다.
7 where 종문(The where clause)
where 종 구 는 자신 이 지정 한 조건 에 따라 더욱 정확 한 인 스 턴 스 를 되 돌려 줄 수 있 습 니 다.

 
   
  1. from eg.Cat as cat where cat.name='Fritz' 

복합 표현 식 은 where 종문 기능 을 매우 강하 게 합 니 다:

 
   
  1. from eg.Cat as cat where cat.name='Fritz'  

이 검색 어 는 연 결 된 SQL 검색 어로 번 역 될 것 입 니 다.
만약 당신 이 이 조 회 를 쓴다 면:

 
   
  1. from eg.Foo foo where foo.bar.baz.customer.address.city is not null 

이 조 회 는 SQL 문 구 를 번역 하려 면 4 개의 표 연결 이 필요 합 니 다.
"="연산 자 는 속성 을 비교 할 수 있 을 뿐만 아니 라 인 스 턴 스 도 비교 할 수 있 습 니 다.

 
   
  1. from eg.Cat cat, eg.Cat rival where cat.mate = rival.mate  
  2.  
  3. select cat, mate  from eg.Cat cat, eg.Cat mate  where cat.mate = mate  

id 라 는 특수 한 속성 은 대상 의 유일한 식별 자 를 참조 하 는 데 사 용 됩 니 다.대상 의 속성 명 을 사용 할 수도 있 습 니 다.

 
   
  1. from eg.Cat as cat where cat.id = 123  
  2.  
  3. from eg.Cat as cat where cat.mate.id = 69    

이 조 회 는 표 연결 이 필요 없 기 때문에 이전 보다 효율 적 이다.
복합 메 인 키 의 속성 을 사용 할 수 있 습 니 다.person 이 medicareNumber 와 country 로 구 성 된 메 인 키 가 있다 고 가정 합 니 다.

 
   
  1. from bank.Person person  
  2.  
  3. where person.id.country = 'AU' 
  4.  
  5. and person.id.medicareNumber = 123456  
  6.  
  7. from bank.Account account  
  8.  
  9. where account.owner.id.country = 'AU' 
  10.  
  11.     and account.owner.id.medicareNumber = 123456  

다시 한 번 반복 하면 두 번 째 조회 효율 이 높다.
마찬가지 로 속성 을 지정 한 클래스 가 다 중 지속(polymorphic persistence)상황 에서 실체 에 접근 하 는 discriminator value 입 니 다.
where 에 포 함 된 자바 클래스 이름 은 discriminator value 로 번 역 됩 니 다.
from eg.Cat cat where cat.class = eg.DomesticCat
구성 요소(component)의 속성 과 사용자 가 정의 하 는 합성 형식(구성 요소 의 구성 요소 등)을 지정 할 수 있 습 니 다.
구성 요소 의 속성 으로 끝 나 는 경로 표현 식 을 영원히 사용 하지 마 십시오.예 를 들 어 store.owner 가 address 구성 요소 라 는 실체 라 고 가정 합 니 다.

 
   
  1. store.owner.address.city    //  
  2.  
  3. store.owner.address        // !  

'any'라 는 유형 은 두 개의 특별한 속성 이 있 습 니 다.하 나 는 id 이 고 다른 하 나 는 class 입 니 다.다음 방법 으로 연결 할 수 있 습 니 다(join).AuditLog.item 은<  any>맵 의 속성:

 
   
  1. from eg.AuditLog log, eg.Payment payment  
  2.  
  3. where log.item.class = 'eg.Payment' and log.item.id = payment.id  

주의해 야 할 것 은 조회 중인 log.item.class 와 payment.class 는 완전히 다른 데이터베이스 열 을 참고 할 것 입 니 다.
8 표현 식(표현 식)
where 문장의 표현 식 은 SQL 의 많은 것 을 사용 할 수 있 습 니 다.
· 수학 연산 자:+,-,*,/
· 이원 비교 연산 자:=,>=,<  =, <  >, !=, like
· 논리 연산 자:and,or,not
· 문자열 연결 문자:||
· SQL 함수:upper()및 lower()
· 괄호:()
· in, between, is null
· JDBC 입력 매개 변수:?
· 지정 한 인자:name,:startdate, :x1
· in 과 between:

 
   
  1. from eg.DomesticCat cat where cat.name between 'A' and 'B' 
  2.  
  3. from eg.DomesticCat cat where cat.name in ( 'Foo''Bar''Baz' )  

부정 형식의(negated forms):

 
   
  1. from eg.DomesticCat cat where cat.name not between 'A' and 'B' 
  2.  
  3. from eg.DomesticCat cat where cat.name not in ( 'Foo''Bar''Baz' )  

· is null 과 is not null
· 특수 한 속성 size 나 size()함수 로 집합 크기 를 측정 할 수 있 습 니 다:

 
   
  1. from eg.Cat cat where cat.kittens.size > 0  
  2.  
  3. from eg.Cat cat where size(cat.kittens) > 0  

·  색인 이 있 는 집합 에 대해 서 는 최소 색인 과 최대 색인 을 참조 하기 위해 특수 속성 minIndex 와 maxIndex 를 사용 할 수 있 습 니 다.마찬가지 로 minElement 와 maxElement 를 사용 하여 기본 형식의 집합 인 minimum 와 maximum 요 소 를 참조 할 수 있 습 니 다.

 
   
  1. from Calendar cal where cal.holidays.maxElement > current date 

함수 형식 일 수도 있 습 니 다.

 
   
  1. from Order order where maxindex(order.items) > 100  
  2.  
  3. from Order order where minelement(order.items) > 10000  

색인 과 요 소 를 집합 할 때(elements and indices 함수)와 전달 서브 조회 결과 집합 을 전달 할 때 SQL 함수 any,some,all,exists,in 은 모두 지원 합 니 다.

 
   
  1. select mother from eg.Cat as mother, eg.Cat as kit  
  2.  
  3. where kit in elements(foo.kittens)  
  4.  
  5. select p from eg.NameList list, eg.Person p  
  6.  
  7. where p.name = some elements(list.names)  
  8.  
  9. from eg.Cat cat where exists elements(cat.kittens)  
  10.  
  11. from eg.Player p where 3 > all elements(p.scores)  
  12.  
  13. from eg.Show show where 'fizard' in indices(show.acts)  

주의:size,elements,indices,minIndex,maxIndex,minElement,maxElement 는 사용 할 때 제한 이 있 습 니 다.
v      where 에서 문장의 in 은 데이터베이스 의 하위 조회 에 만 사 용 됩 니 다.
v      select 종문 의 in 은 elements 와 indices 함수 에 만 사 용 됩 니 다.
v      색인 요소 가 있 는 collection(arrays,lists,maps)은 where 에서 만 색인 을 통 해 참조 할 수 있 습 니 다.

 
   
  1. from Order order where order.items[0].id = 1234  
  2.  
  3. select person from Person person, Calendar calendar  
  4.  
  5. where calendar.holidays['national day'] = person.birthDay  
  6.  
  7.     and person.nationality.calendar = calendar  
  8.  
  9. select item from Item item, Order order 
  10.  
  11. where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11  
  12.  
  13. select item from Item item, Order order 
  14.  
  15. where order.items[ maxindex(order.items) ] = item and order.id = 11  

표현 식 의[]내 부 는 산술 표현 식 일 수 있 습 니 다.

 
   
  1. select item from Item item, Order order 
  2.  
  3. where order.items[ size(order.items) - 1 ] = item  

HQL 은 one-to-many 관련 값 의 집합 에 내 장 된 index()함 수 를 제공 합 니 다.

 
   
  1. select item, index(item) from Order order 
  2.  
  3.     join order.items item  
  4.  
  5. where index(item) <  5  

특정 데이터베이스 에서 지원 하 는 SQL 함 수 를 사용 할 수 있 습 니 다:

 
   
  1. from eg.DomesticCat cat where upper(cat.namelike 'FRI%' 

위의 모든 것 을 믿 지 않 는 다 면 더 길 고 더 짧 은 읽 을 수 있 는 조 회 를 생각해 보 세 요.

 
   
  1. select cust  
  2. from Product prod,  
  3.     Store store  
  4.     inner join store.customers cust  
  5. where prod.name = 'widget' 
  6.     and store.location.name in ( 'Melbourne''Sydney' )  
  7.     and prod = all elements(cust.currentOrder.lineItems) 

알림:something like

 
   
  1. SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order  
  2. FROM customers cust,  
  3.     stores store,  
  4.     locations loc,  
  5.     store_customers sc,  
  6.     product prod  
  7. WHERE prod.name = 'widget' 
  8.     AND store.loc_id = loc.id  
  9.     AND loc.name IN ( 'Melbourne''Sydney' )  
  10.     AND sc.store_id = store.id  
  11.     AND sc.cust_id = cust.id  
  12.     AND prod.id = ALL(  
  13.         SELECT item.prod_id  
  14.         FROM line_items item, orders o  
  15.         WHERE item.order_id = o.id  
  16. AND cust.current_order = o.id) 

좋은 웹페이지 즐겨찾기