[JPA] 쿼리메서드 : 쿼리 연습 조회(findBy..) , 페이징처리

 
 
 
 
 
 

[JPA] 쿼리메서드 : 쿼리 연습 조회(findBy..) 
JPA에서 사용하는 Named Query나 JPQL(Java Persistence Query Language), Query dsl 학습이 필요

* 쿼리 메소드 이용
- Spring Data JPA는 메소드의 이름만으로 원하는 질의(query)를 실행, 단 SELECT에 해당
- find .. By 쿼리 메소드를 작성시 find뒤에 엔티티 타입지정, By뒤엔 칼럼명;
  ex) 'findBoardByTitle' >> Board 테이블의 Title 칼럼
  ex) 'findBoardByTitle("제목177")
- 리턴 타입은 Page<T>, Slice<T>, List<T> 와 같은 Collection<T>형태

 

- findBy..로시작하는 쿼리 메소드는 지정하는 속상의 값에 따라 파라미터 타입이 결정된다.

Keyword
Sample
JPQL snippet
And
findByLastnameAndFirstname
where x.lastname=?1 and x.firstname=?2
Or
findByLastnameOrFirstname
where x.lastname=?1 or x.firstname=2
Between
findByStartDateBetween
where x.startDate between 1? and ?2
LessThan
findByAgeLessThan
where x.age < ?1
GreaterThan
findByAgeGreaterThan
where x.age > ?1
IsNull
findByAgeIsNull
where x.age is null
IsNotNull, NotNull
findByAge(Is)NotNull
where x.age not null
Like
findByFirstnameLike
where x.firstname like ?1
NotLike
findByFirstnameNotLike
where x.firstname not like ?1
StartingWith
findByFirstnameStartingWith
where x.firstname like ?1 (parameter bound with appended %)
EndingWith
findByFirstnameEndingWith
where x.firstname like ?1 (parameter bound wrappend in %)
OrderBy
findByAgeOrderByLastnameDesc
where x.age = ?1 order by x.lastname desc
Not
findByLastnameNot
where x.lastname <> ?1
In
findByAgeIn(Collection<Age>ages)
where x.age in ?1
NotIn
findByAgeNotIn(Collection <Age>age)
where x.age not in ?1
True
findByAcitiveTrue()
where x.active = true
False
findByActiveFalse()
where x.active = false
 

* like 구문 처리
① 단순한 like >> Like
② 키워드 + '%' >> StartingWith
③ '%' + 키워드 >> EndingWith
④ '%' + 키워드 + '%' >> Containing
ex) '05' 라는 문자 게시글 검색
- Repository Interface ▶ public Collection<Board> findByTitleContaining(String title);
- 호출 ▶ Collection<Board> results = repo.findByTitleContaining("05");
- 결과 ▶ 타이틀(Title) 칼럼에서 '05'가 포함(Containing)된 데이터 조회
- SQL ▶ WHERE title LIKE '%05%'; 


*and 혹은 or 조건 처리
속성이 두개 이상일때는 파라미터 역시 속성의 수만큼 맞춤
- public Collection<Board> findByTitleContatiningOrContentContaining(String title, String content);
- 호출 ▶ Collection<Board> results = repo.findByTitleContaining("05","a");

- SQL ▶ WHERE title LIKE '%05%' OR title '%a%' ; 

*부등호 처리
Repository Interface ▶ public Collection<Board> findByTitleContatiningAndBnoGreaterThan(String keywoard,Long num);
- 호출 ▶ Collection<Board> results = repo.findByTitleContatiningAndBnoGreaterThan("5",50L);

- 결과 ▶ 제목(Title)에 '5' 가 포함(Containing)되어있고 번호(Bno)가 50보다 큰(GreaterThan) 데이터 조회
- SQL ▶ WHERE title LIKE '%5%' AND bno > 50


*order by처리
- Asc 
- Desc (역순)
Repository Interface ▶ public Collection<Board> findByBnoGreaterThanOrderByBnoDesc(Long num);
- 호출 ▶ Collection<Board> results = repo.findByBnoGreaterThanOrderByBnoDesc(90L);

- 결과 ▶ 번호(Bno)가 90보다 큰(GreaterThan) 데이터를 번호(Bno)기준으로 역순(Desc)으로 정렬(OrderBy)
- SQL ▶ WHERE bno>90 ORDER BY bno DESC

 

: 쿼리메소드들은 마지막 파라미터로 Pageable 인터페이스, Sort 인터페이스 를 사용할수 있다.

* Pageable 인터페이스 ‥ 페이지처리 / Sort 인터페이스 ‥ 정렬
- org.springframework.data.domain.Pageable 인터페이스를 구현한 클래스 중 PageRequest 클래스 이용

[주의]
PageRequestd 의 경우 스프링부트의 버전에 주의
2.0 >> new PageRequest()는 deprecated 때문에 사용하면 안되고, PageRequest.of()를 사용

▼ PageRequest의 생성자

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

생성자
설명
PageRequest (int page, int size)
페이지번호, 페이지당 데이터수
PageRequest(int page, int size
, Sort.Direction direction, String .. props)
페이지번호, 페이지당 데이터수, 정렬방향, 속성(칼럼)들
PageRequest (int page, int size, Sort sort)
페이지번호, 페이지당 데이터수, 정렬 방향
// >> Repository Interface //bno>? ORDER BY bno DESC LIMIT ?,? public List<Board> findByBnoGreaterThanOrderByBnoDesc(Long bno, Pageable paging); // >> 호출 //1번:: where board0_.title like ? limit ? Pageable paging = new PageRequest(0,10); // (인텍스번호는 0부터 시작하며, 10견의 데이터를 조회 //2번:: where board0_.title like ? order by board0_.bno asc limit ? Pageable paging = new PageRequest(0,10,Sort.Direction.ASC,"bno"); boardRepo.findBoardByTitleContaining("5",paging).forEach(board->System.out.println(board));

- Console에 나온 SQL문 >> .. where board0_.title like ? limit ?
- MySQL 이기 때문에 자동 limit가 적용


- 1번 방법 (페이징)
Pageable paging = new PageRequest(0,10); 
SQL >> where board0_.title like ? limit ?


- 2번 방법 (페이징+정렬)
Pageable paging = new PageRequest(0,10,Sort.Direction.ASC,"bno");
SQL >> where board0_.title like ? order by board0_.bno asc limit ?

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
49 org.eclipse.ui.navigator Class CommonViewer 졸리운_곰 2019.07.04 398
48 MessageBox Example : Dialog « SWT JFace Eclipse « Java file 졸리운_곰 2019.06.16 362
47 Add Table Selection Listener and Get Selected TableItem : Table Event « SWT « Java Tutorial file 졸리운_곰 2019.06.16 372
46 Building and delivering a table editor with SWT/JFace file 졸리운_곰 2019.06.16 430
45 Demonstrates CellEditors : Table « SWT JFace Eclipse « Java file 졸리운_곰 2019.06.16 279
44 Demonstrates TableViewers : Table « SWT JFace Eclipse « Java file 졸리운_곰 2019.06.16 323
43 Eclipse RCP Tutorial: How to Add a Progress Bar file 졸리운_곰 2015.11.07 457
42 SWT Custom Widgets - Tutorial file 졸리운_곰 2015.08.23 379
41 Show a tool tip inside a rectangle : ToolTip « SWT « Java Tutorial file 졸리운_곰 2015.08.22 285
40 [SWT, Java] Tooltip example 졸리운_곰 2015.08.22 270
39 [SWT, Java], Button by Image, 이미지로 버튼 생성 졸리운_곰 2015.08.22 416
38 [SWT] Image Button 졸리운_곰 2015.08.22 277
37 [SWT] eventListener에서 부모 class (이벤트발생 클래스) 얻기 졸리운_곰 2015.08.16 340
36 [SWT] MessageBox Example file 졸리운_곰 2015.08.16 494
35 [SWT] How to create your own dialog classes file 졸리운_곰 2015.08.16 347
34 [SWT] Number Input Dialog file 졸리운_곰 2015.08.16 275
33 [SWT] Demonstrates a Canvas file 졸리운_곰 2015.08.12 268
32 SWT Control in One Example file 졸리운_곰 2015.08.10 403
31 SWT Tree With Multi columns file 졸리운_곰 2015.08.06 374
30 SWT Tree Composite 졸리운_곰 2015.08.06 289
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED