Spring

Spring Boot STEP 7 - JPA 2

2023. 7. 3. 10:38
728x90

★ 검색 확인 연산자

  • null 값 확인
//[Is}Null, [Is]NotNull
//- 컬럼 값이 null인 레코드 검색

//[Is]Empty, [Is]NotEmpty
//- 컬럼값이 null이거나 빈문자열인 레코드 검색
  • null 값 확인 ex)
List<Item> list = itemRepo.findByOwnerNull();
List<Item> list = itemRepo.findByOwnerEmpty();

List<Item> list = itemRepo.findByOwnerNotNull();
  • 정렬 
//정렬
//List<Item> list = itemRepo.findAll(Sort.by(Sort.Direction.ASC, "price"));

//List<Item> list = itemRepo.findAll(Sort.by("name")); //오름차순

//List<Item> list = itemRepo.findAllByOrderByColorDesc();

//List<Item> list = itemRepo.findAllByOrderByColorDesc("홍길동");
  • 관계연산자
//[Is]GreaterThan, [Is]LessThan, [Is]Between
//[Is]GreaterThanEqual, [Is]LessThanEqual

//List<Item> list = itemRepo.findByPriceGreaterThan(100000, Sort.by("price"));

//List<Item> list = itemRepo.findByPriceLessThan(100000);
		
//List<Item> list = itemRepo.findByPriceBetween(90000, 120000);

//List<Item> list = itemRepo.findByOrderdateBetween("2023-06-25", "2023-06-27");
  • IgnoreCase : 특정 컬럼의 대소문자를 구분하지 않고 검색
//List<Item> list = itemRepo.findByColorIgnoreCase("white");
//where upper(color) = upper(?)
  • In, NotIn : where color in ('yellow', 'blue')
/*
List<String> colors = new ArrayList<String>();
colors.add("yellow");
colors.add("blue");

List<Item> list = itemRepo.findByColorIn(colors);
*/

List<Item> list = itemRepo.findByOwnerIn(new String[]{"홍길동", "아무개"});

// NotIn
List<Item> list = itemRepo.findByOwnerNotIn(new String[]{"홍길동", "아무개"});

 

★ 도메인 클래스 컨버터(Domain Class Converter)

  • PK를 넘겨서, 바로 Entity를 조회할 수 있다.
@GetMapping("/item/m14/{name}")
public String m14(Model model, @PathVariable("name") Item result) {

    //item/m13?name=마우스
    //item/m14/마우스
    model.addAttribute("result", result);


    return "item/result";
}
  • First/Top
//Item result = itemRepo.findFirstByOrderByPriceAsc();
//Item result = itemRepo.findTopByOrderByPriceAsc();

//model.addAttribute("result", result);

List<Item> list = itemRepo.findTop3ByOrderByPriceDesc();

 

★ 페이징, Paging

@GetMapping("/item/m16")
public String m16(Model model, int page) {

    PageRequest pageRequest = PageRequest.of(page, 5, Sort.by("name"));

    List<Item> list = itemRepo.findPageListBy(pageRequest);

    model.addAttribute("list", list);

    return "item/result";
}

 

★ 사용자 쿼리 작성

  • 모든 컬럼 가져오기
//@Query
//- 사용자 쿼리 작성
//- 쿼리 메소드 키워드로 작성 불가능 쿼리 > 직접 SQL 작성

//select * from Item

List<Item> list = itemRepo.findAllItem();
  • 특정 색상 컬럼 가져오기 
@GetMapping("/item/m18")
public String m18(Model model, String color) {

    List<Item> list = itemRepo.findAllItemByColor(color);

    model.addAttribute("list", list);

    return "item/result";
}

 

★ ItemRepository.java

//JpaRepository <엔티티타입, PK자료형>
//- ItemRepository > 이름은 자유
//- 엔티티명 > Repository

public interface ItemRepository extends JpaRepository<Item, String> {
	
	//추상 메소드
	//1. JpaRepository 상속 메소드 > 기본
	//2. 사용자 정의 메소드 > 확장
	
	Item findByName(String name);
	Item findByNameIs(String name);
	Item findByNameEquals(String name);
	
	Item findByPrice(int price);
	
	Item findByColorAndOwner(String color, String owner);
	Item findByColorAndOwnerAndPrice(String color, String owner, int price);
	
	//Item findByColorOrOwner(String color, String owner);
	Item findByColorOrPrice(String color, int price);
	
	List<Item> findByColor(String color);
	
	List<Item> findByColor(String color, Sort sort);
	
	List<Item> findByColorAndPrice(String color, int price);
	List<Item> findByColorOrOwner(String color, String owner);
	
	List<Item> findByNameLike(String word);
	
	List<Item> findByNameEndingWith(String word);
	
	//List<Item> findByOwnerNull();
	List<Item> findByOwnerNotNull();
	
	List<Item> findAllByOrderByColor();
	
	List<Item> findAllByOrderByColorDesc();
	//List<Item> findAllByOrderByColorDesc(String string);
	List<Item> findByPriceGreaterThan(int i, Sort by);
	List<Item> findByPriceLessThan(int i);
	List<Item> findByPriceBetween(int min, int max);
	List<Item> findByOrderdateBetween(String string, String string2);
	
	List<Item> findByColorIgnoreCase(String string);
	List<Item> findByColorIn(List<String> colors);
	List<Item> findByOwnerIn(String[] strings);
	List<Item> findByOwnerNotIn(String[] strings);
	Item findFirstByOrderByPriceAsc();
	Item findTopByOrderByPriceAsc();
	List<Item> findTop3ByOrderByPriceDesc();
	List<Item> findPageListBy(PageRequest pageRequest);
	
	@Query(value="select * from Item", nativeQuery = true)
	List<Item> findAllItem();
	
	//JPQL > Java Persistence Query Language
	@Query(value="select * from Item where color = :color", nativeQuery = true)
	List<Item> findAllItemByColor(@Param("color") String color);
}

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'Spring' 카테고리의 다른 글

Spring Boot STEP 6 - JPA  (0) 2023.07.01
Spring Boot STEP 5 - Thymeleaf3  (0) 2023.06.29
Spring Boot STEP 4 - Thymeleaf2  (0) 2023.06.28
Spring Boot STEP 3 - Thymeleaf  (0) 2023.06.27
Spring Boot STEP 2 - 기본적인 CRUD 사용  (0) 2023.06.26
'Spring' 카테고리의 다른 글
  • Spring Boot STEP 6 - JPA
  • Spring Boot STEP 5 - Thymeleaf3
  • Spring Boot STEP 4 - Thymeleaf2
  • Spring Boot STEP 3 - Thymeleaf
IT의 큰손
IT의 큰손
IT계의 큰손이 되고 싶은 개린이의 Log 일지
IT의 큰손
Developer Story House
IT의 큰손
전체
오늘
어제
  • 분류 전체보기 (457)
    • 정보처리기사 필기 (18)
    • 정보처리기사 실기 (12)
    • 정보처리기사 통합 QUIZ (12)
    • 빅데이터 (11)
    • 안드로이드 (11)
    • 웹페이지 (108)
    • 자바 (49)
    • SQLD (3)
    • 백준 알고리즘 (76)
    • 데이터베이스 (41)
    • 깃허브 (2)
    • Library (14)
    • Server (31)
    • 크롤링&스크래핑 (3)
    • Spring (23)
    • Vue.js (13)
    • React (27)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Developer Stroy House

인기 글

태그

  • 정보처리기사
  • html
  • css
  • 정보처리기사필기
  • 백엔드
  • IT자격증
  • 웹페이지
  • 정보보안전문가
  • 웹개발자
  • 데이터베이스
  • 백준
  • jsp
  • 개발블로그
  • 앱개발자
  • 알고리즘
  • DB
  • React
  • 웹개발
  • 개발자
  • it
  • IT자격증공부
  • jquery
  • ajax
  • JavaScript
  • IT개발자
  • 자바
  • DBA
  • java
  • 프론트엔드
  • 코딩테스트

최근 댓글

최근 글

Designed By hELLO
IT의 큰손
Spring Boot STEP 7 - JPA 2
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.