Hibernate 쿼 리 언어 HQL 8 대 요점
41094 단어 Hibernate
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 검색 은 다음 과 같 습 니 다.
- from eg.Cat
eg.Cat 류 의 모든 인 스 턴 스 를 간단하게 되 돌려 줍 니 다.
검색 의 다른 부분 에서 Cat 를 참조 해 야 할 수도 있 기 때문에 클래스 에 별명(alias)을 설정 해 야 할 때 가 많 습 니 다.
- from eg.Cat as cat
키워드 as 는 선택 할 수 있 습 니 다.우 리 는 다음 과 같이 쓸 수 있 습 니 다.
- from eg.Cat cat
여러 종류 가 나타 나 면'피리 카드 축적'이나 교차 연결 을 되 돌려 줍 니 다.
- from Formula as form, Parameter as param
HQL 의 별명 은 소문 자로 자바 로 컬 변수의 명명 규범 에 부합 하 는 좋 은 습관 입 니 다.
3 연결 및 연결(Associations and joins)
우 리 는 별명 관련 실체,심지어 join 으로 관련 값 의 집합 요 소 를 사용 합 니 다.
- from eg.Cat as cat
-
- inner join cat.mate as mate
-
- left outer join cat.kittens as kitten
-
- from eg.Cat as cat left join cat.mate.kittens as kittens
-
- 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 은 간략하게 쓸 수 있 습 니 다.
- from eg.Cat as cat
-
- join cat.mate as mate
-
- left join cat.kittens as kitten
또한,"fetch"연결 은 부모 대상 과 함께 초기 화 할 수 있 도록 단일 연결 을 사용 하여 연결 하거나 값 의 집합 을 허용 합 니 다.이것 은 Collection 을 사용 하 는 상황 에서 특히 유용 하 다.
- from eg.Cat as cat
-
- inner join fetch cat.mate
-
- left join fetch cat.kittens
fetch join 은 보통 별명 을 설정 할 필요 가 없습니다.연 결 된 대상 은 where 종문 에 사용 되 어 서 는 안 되 고 다른 종문 에 도 사용 할 수 없 기 때 문 입 니 다.
연 결 된 대상 은 검색 결과 에서 직접 돌아 갈 수 없고 부모 대상 을 통 해 접근 할 수 있 습 니 다.
주의:현재 구현 중 검색 에서 하나의 집합 만 되 돌아 갈 수 있 습 니 다.또한 fetch 는 scroll()과 iterator()가 호출 한 조회 에 사용 되 지 않 을 수도 있 습 니 다.마지막 으로 full join fetch 와 right join fetch 는 의미 가 없다 는 점 을 주의해 야 한다.
4 select 종문(The select clause)
select 는 문장 에서 결과 에 집중 적 으로 돌아 오 는 대상 과 속성 을 선택 합 니 다:
- select cat.mate from eg.Cat cat
위의 이 조 회 는 모든 고양이 의 배우자 에 게 돌아간다.
너 도 elements 함 수 를 사용 하여 집합 요 소 를 되 돌려 줄 수 있다.다음 조 회 는 고양이(Cat)의 모든 고양이(Kitten)를 되 돌려 줍 니 다.
- select elements(cat.kittens) from eg.Cat cat
검색 도 모든 값 형식(Component 형식의 속성 포함)의 속성 을 되 돌려 줍 니 다.
- select cat.name from eg.DomesticCat cat
-
- where cat.name like 'fri%'
-
- select cust.name.firstName from Customer as cust
조 회 는 여러 대상 을 되 돌려 줄 수도 있 고 Object[]형식의 배열 의 속성 을 되 돌려 줄 수도 있 습 니 다.
- select mother, offspr, mate.name
-
- from eg.DomesticCat as mother
-
- inner join mother.mate as mate
-
- left outer join mother.kittens as offspr
또는 실제 자바 대상 으로:
- select new Family(mother, mate, offspr)
-
- from eg.DomesticCat as mother
-
- join mother.mate as mate
-
- left join mother.kittens as offspr
위의 이 검색 어 는 Family 류 에 적당 한 구조 함수 가 있다 고 가정 합 니 다.
5 집합 함수(Aggregate functions)
검색 은 속성의 집합 함 수 를 사용 할 수 있 습 니 다:
- 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 에서 같 습 니 다.
- select distinct cat.name from eg.Cat cat
-
- select count(distinct cat.name), count(cat) from eg.Cat cat
6 다 중(polymorphism)
from eg.Cat as cat,Cat 뿐만 아니 라 DomesticCat(집 고양이)같은 하위 클래스 도 있 습 니 다.Hibernate 는 from 에서 문장 에서 자바 류 와 인 터 페 이 스 를 지정 할 수 있 습 니 다.조 회 는 이 클래스 와 이 인 터 페 이 스 를 계승 한 모든 영구적 인 인 인 스 턴 스 를 되 돌려 줍 니 다.다음 조 회 는 모든 오래된 대상 을 되 돌려 줍 니 다:
- from java.lang.Object o
지정 한 인 터 페 이 스 는 여러 개의 서로 다른 지구 류 에 의 해 실 현 될 수 있 습 니 다.
- from eg.Named n, eg.Named m where n.name = m.name
마지막 두 개의 조 회 는 1 개의 SQL 을 초과 하 는 select 가 필요 합 니 다.이것 은 문장 에서 지정 한 배열 순서에 따라 전체 결과 집합 을 배열 할 수 없다 는 것 을 의미 합 니 다.이것 은 또한 이 검색 어 를 Query.scroll()로 호출 할 수 없다 는 것 을 의미한다.
7 where 종문(The where clause)
where 종 구 는 자신 이 지정 한 조건 에 따라 더욱 정확 한 인 스 턴 스 를 되 돌려 줄 수 있 습 니 다.
- from eg.Cat as cat where cat.name='Fritz'
복합 표현 식 은 where 종문 기능 을 매우 강하 게 합 니 다:
- from eg.Cat as cat where cat.name='Fritz'
이 검색 어 는 연 결 된 SQL 검색 어로 번 역 될 것 입 니 다.
만약 당신 이 이 조 회 를 쓴다 면:
- from eg.Foo foo where foo.bar.baz.customer.address.city is not null
이 조 회 는 SQL 문 구 를 번역 하려 면 4 개의 표 연결 이 필요 합 니 다.
"="연산 자 는 속성 을 비교 할 수 있 을 뿐만 아니 라 인 스 턴 스 도 비교 할 수 있 습 니 다.
- from eg.Cat cat, eg.Cat rival where cat.mate = rival.mate
-
- select cat, mate from eg.Cat cat, eg.Cat mate where cat.mate = mate
id 라 는 특수 한 속성 은 대상 의 유일한 식별 자 를 참조 하 는 데 사 용 됩 니 다.대상 의 속성 명 을 사용 할 수도 있 습 니 다.
- from eg.Cat as cat where cat.id = 123
-
- from eg.Cat as cat where cat.mate.id = 69
이 조 회 는 표 연결 이 필요 없 기 때문에 이전 보다 효율 적 이다.
복합 메 인 키 의 속성 을 사용 할 수 있 습 니 다.person 이 medicareNumber 와 country 로 구 성 된 메 인 키 가 있다 고 가정 합 니 다.
- 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
다시 한 번 반복 하면 두 번 째 조회 효율 이 높다.
마찬가지 로 속성 을 지정 한 클래스 가 다 중 지속(polymorphic persistence)상황 에서 실체 에 접근 하 는 discriminator value 입 니 다.
where 에 포 함 된 자바 클래스 이름 은 discriminator value 로 번 역 됩 니 다.
from eg.Cat cat where cat.class = eg.DomesticCat
구성 요소(component)의 속성 과 사용자 가 정의 하 는 합성 형식(구성 요소 의 구성 요소 등)을 지정 할 수 있 습 니 다.
구성 요소 의 속성 으로 끝 나 는 경로 표현 식 을 영원히 사용 하지 마 십시오.예 를 들 어 store.owner 가 address 구성 요소 라 는 실체 라 고 가정 합 니 다.
- store.owner.address.city //
-
- store.owner.address // !
'any'라 는 유형 은 두 개의 특별한 속성 이 있 습 니 다.하 나 는 id 이 고 다른 하 나 는 class 입 니 다.다음 방법 으로 연결 할 수 있 습 니 다(join).AuditLog.item 은< any>맵 의 속성:
- from eg.AuditLog log, eg.Payment payment
-
- 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:
- from eg.DomesticCat cat where cat.name between 'A' and 'B'
-
- from eg.DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )
부정 형식의(negated forms):
- from eg.DomesticCat cat where cat.name not between 'A' and 'B'
-
- from eg.DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )
· is null 과 is not null
· 특수 한 속성 size 나 size()함수 로 집합 크기 를 측정 할 수 있 습 니 다:
- from eg.Cat cat where cat.kittens.size > 0
-
- from eg.Cat cat where size(cat.kittens) > 0
· 색인 이 있 는 집합 에 대해 서 는 최소 색인 과 최대 색인 을 참조 하기 위해 특수 속성 minIndex 와 maxIndex 를 사용 할 수 있 습 니 다.마찬가지 로 minElement 와 maxElement 를 사용 하여 기본 형식의 집합 인 minimum 와 maximum 요 소 를 참조 할 수 있 습 니 다.
- from Calendar cal where cal.holidays.maxElement > current date
함수 형식 일 수도 있 습 니 다.
- from Order order where maxindex(order.items) > 100
-
- from Order order where minelement(order.items) > 10000
색인 과 요 소 를 집합 할 때(elements and indices 함수)와 전달 서브 조회 결과 집합 을 전달 할 때 SQL 함수 any,some,all,exists,in 은 모두 지원 합 니 다.
- select mother from eg.Cat as mother, eg.Cat as kit
-
- where kit in elements(foo.kittens)
-
- select p from eg.NameList list, eg.Person p
-
- where p.name = some elements(list.names)
-
- from eg.Cat cat where exists elements(cat.kittens)
-
- from eg.Player p where 3 > all elements(p.scores)
-
- 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 에서 만 색인 을 통 해 참조 할 수 있 습 니 다.
- 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
표현 식 의[]내 부 는 산술 표현 식 일 수 있 습 니 다.
- select item from Item item, Order order
-
- where order.items[ size(order.items) - 1 ] = item
HQL 은 one-to-many 관련 값 의 집합 에 내 장 된 index()함 수 를 제공 합 니 다.
- select item, index(item) from Order order
-
- join order.items item
-
- where index(item) < 5
특정 데이터베이스 에서 지원 하 는 SQL 함 수 를 사용 할 수 있 습 니 다:
- from eg.DomesticCat cat where upper(cat.name) like 'FRI%'
위의 모든 것 을 믿 지 않 는 다 면 더 길 고 더 짧 은 읽 을 수 있 는 조 회 를 생각해 보 세 요.
- 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)
알림:something like
- 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)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[JPA] 즉시로딩(EAGER)과 지연로딩(LAZY) (왜 LAZY 로딩을 써야할까?) (1)Proxy는 이 글의 주제인 즉시로딩과 지연로딩을 구현하는데 중요한 개념인데, 일단 원리는 미뤄두고 즉시로딩과 지연로딩이 무엇인지에 대해 먼저 알아보자. 눈 여겨 볼 곳은 'fetch = FetchType.EAGER...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.