JPA 메서드 만들기

minjjai·2022년 10월 7일
0

개요

spring boot를 사용해 웹 개발을 하는 사람이라면, 보통 JPA에 대해서 알고 있을 것이다.
나 역시도 이번 qna사이트 만들기 프로젝트를 하며 간단한 JPA사용법에 대해서 익혔다.

spring boot에서는 controller -> service -> repository 이렇게 메서드 호출을 하고, 응답 데이터가 반대로 간다.

repository는 JpaRepository를 상속하는 인터페이스로 만들면 service에서 repository의 메서드를 일부 바로 호출할 수 있다.
예로 들면,

  • findById
  • findAll
    ..

등의 메서드들은 바로 사용할 수 있다.
반면에 특정한 규칙을 따라 생성한 메서드들은 추상메서드로 인터페이스인 repository안에 만들어주면 제 기능을 하도록 할 수 있다.
그 규칙을 간단하게 써보려 한다.

JPA메서드 생성

종류

  • And
  • Or
  • LessThan
  • GreaterThan
  • Equal
  • Like
  • In
  • OrderBy

Ex)

@Repository
public interface ArticleRepository extends JpaRepository<Article, Long> {
	//subject and content
	findBySubjectAndContent(String subject, String content)	
    
    //subject or content
	findBySubjectOrContent(String subject, String content)	
    
    //fromDate <= CreateDate <= toDate
	findByCreateDateBetween(LocalDateTime fromDate, LocalDateTime toDate)	
    
    //Id < id ~보다 작은
	findByIdLessThan(Integer id)	
    
    //Id >= id ~보다 크거나 같은
	findByIdGraterThanEqual(Integer id)	
    
    //subject를 포함하는
	findBySubjectLike(String subject)	
    
    //주어진 배열 안에 있는
	findBySubjectIn(String[] subjects)	
    
    //검색 결과를 CreateDate로 오름차순 정렬하여
	findBySubjectOrderByCreateDateAsc(String subject)
}

이외에도 더 복잡하게 메서드들을 만들 수 있다.
더 자세하고 복잡한 것들은 다음에 알아보도록 하자

profile
BackEnd Developer

0개의 댓글