기본 생성조건
: 테이블마다 생성하는 것을 권장
기본 구현 방법 (JPA기준)
: 단순히 JpaRepository를 상속하는 것 만으로도 CRUD가 가능하다. (save, delete 등)
: findById같은 기본 문법은 따로 선언하지 않아도 사용이 가능하다
: <객체명, 식별자> 지정
public interface AnswerRepository extends JpaRepository<Answer, Long> {
}
메서드 선언 방법
1. 기본 객체 꺼내기
: Optional<객체명> 방식으로 꺼낼 수 있다. Optional에서 객체를 꺼내려면, .get()을 사용
Optional<Answer> findById(Long id);
2. Page로 꺼내기
: Page<객체명> 방식으로 꺼낼 수 있다. 파라미터에 pageable이 들어가야하며, 다른 파라미터도 추가 가능하다.
Page<Answer> findAllByOrderByIdDesc(Pageable pageable);
@EntityGraph(attributePaths = {"question", "account"})
@Query(value = "select answer from Answer answer where answer.question.id = :questionId")
Page<Answer> findByQuestionWithAll(@Param("questionId") Long questionId, Pageable pageable);
사용할 수 있는 애너테이션 옵션
1. @Query
: JPQL 문으로 된 쿼리를 날리는 커스텀 쿼리 메서드를 만들때 사용 ( 참고링크 https://radpro.tistory.com/398 )
: 예시 코드
1) Answer를 answer로 변수설정하여, answer를 가져온다.
2) answer안의 question에 question을 조인할 것이다.
3) 이때, answer의 id필드값이 @Param으로 주어진 파라미터랑 일치하는 값만 가져온다.
@Query("select answer from Answer answer " +
"join fetch answer.question question where answer.id = :answerId")
2. EntityGraph ( 참고링크 https://freedeveloper.tistory.com/155 )
: Entity 클래스에서 연관관계 매핑 Entity의 정보를 함께 불러올 때 사용 (Fetch기능)
: attributePaths 옵션을 사용해서 필요한 엔티티 값을 지정할 수 있다
: 반드시, 해당 Entity 클래스에 상대 Entity클래스 이름으로 필드 선언 및 매핑이 되어 있어야 한다
: 값을 가져오는 조건은 매핑에서 정한다. (LAZY, EAGER 등)
: @OneToMany의 디폴트조건은 LAZY, @ManyToOne의 디폴트조건은 EAGER
: 변경은 @OneToMany(fetch = FetchType.EAGER) 방식
: 예시코드
// Entity 내 매핑된 필드
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_id")
private Account account;
// Ropository에 적용된 애너테이션
@EntityGraph(attributePaths = {"question", "account"})
@Query("select answer from Answer answer " +
"join fetch answer.question question where answer.id = :answerId")
Optional<Answer> findByIdWithQuestion(@Param("answerId") Long answerId);
'Java & Spring > 프로젝트 기본 설정' 카테고리의 다른 글
| [SpringBoot] Advice (진행중) (0) | 2022.10.20 |
|---|---|
| [SpringBoot] Exception (진행중) (0) | 2022.10.20 |
| [SpringBoot] Entity (진행중) (0) | 2022.10.20 |
| [SpringMVC] 기본 구조 (0) | 2022.10.18 |
| [SpringBoot] Service (진행중) (0) | 2022.10.17 |