Java

스프링부트 JPA Repository

dong99 2024. 4. 18. 23:35

Repository 구현하는 규칙

JPA는 메소드 이름만으로 쿼리를 생성할 수 있다.

위에서 작성한 List<Comment> findAllByPostId(Long post_id); 해당 구문을 보면 해석해 보면 findAll (comment) 전부 찾아볼건데 postId로 찾는다는 거다. 이렇게만 작성해주면 JPA가 알아서 SQL문을 생성해준다.

Method

 method  기능
 save()  레코드 저장 (insert, update)
 findOne()  primary key로 레코드 한건 찾기
 findAll()  전체 레코드 불러오기. 정렬(sort), 페이징(pageable) 가능
 count()  레코드 갯수
 delete()  레코드 삭제

Keyword

메서드 이름 키워드  샘플  설명
 And  findByEmailAndUserId(String email, String userId)  여러필드를 and 로 검색
 Or  findByEmailOrUserId(String email, String userId)  여러필드를 or 로 검색
 Between  findByCreatedAtBetween(Date fromDate, Date toDate)  필드의 두 값 사이에 있는 항목 검색
 LessThan  findByAgeGraterThanEqual(int age)  작은 항목 검색
 GreaterThanEqual  findByAgeGraterThanEqual(int age)  크거나 같은 항목 검색
 Like  findByNameLike(String name)  like 검색
 IsNull  findByJobIsNull()  null 인 항목 검색
 In  findByJob(String … jobs)  여러 값중에 하나인 항목 검색
 OrderBy  findByEmailOrderByNameAsc(String email)  검색 결과를 정렬하여 전달

이 정도만 알고있으면 우리가 사용하려는 대부분의 쿼리문은 이런식으로 작성이 가능하다고 하다.

그리고 외우지 않아도 IDE에 자동완성 기능이 있기 때문에 훨씬 수월하게 개발을 할 수 있게 도와준다.

여기서 컬럼명이나 해당 개체의 필드명들은 파스칼로 적어주는게 좋다고 한다.

위 표말고도 JPA 참조문서를 찾아보면 더 많은 예시를 볼 수 있다.

https://docs.spring.io/spring-data/jpa/docs/1.10.1.RELEASE/reference/html

 

Spring Data JPA - Reference Documentation

Example 11. Repository definitions using Domain Classes with mixed Annotations interface JpaPersonRepository extends Repository { … } interface MongoDBPersonRepository extends Repository { … } @Entity @Document public class Person { … } This example

docs.spring.io

 

출저 : https://geonoo.tistory.com/149