Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Study Repository 외래키 조회 네이밍 수정 #108

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public AssignmentDetailResponse create(AssignmentRequest assignmentRequest, Long
assignmentRequest.getPhoto())
);

List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByStudyId(assignmentRequest.getStudyId());
List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByStudy_Id(assignmentRequest.getStudyId());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이렇게 되면 굳이 Study 도메인 객체를 찾아오지 않고도 조회가 되니 쿼리를 줄일 수 있어 좋은 것 같아요!
너무 좋았습니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 쿼리도 실제로 잘 나가는지 확인해보셨나요? 갑자기 궁금해서 질문 남깁니다!

Copy link
Contributor Author

@HanKwanJin HanKwanJin Mar 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

select
            studymembe0_.member_study_id as member_s1_16_,
            studymembe0_.leader as leader2_16_,
            studymembe0_.member_id as member_i3_16_,
            studymembe0_.study_id as study_id4_16_ 
        from
            study_member studymembe0_ 
        left outer join
            study study1_ 
                on studymembe0_.study_id=study1_.study_id 
        where
            study1_.study_id=?

저도 확인을 안해봤어서 방금 확인 결과 (예시)findByStudyId 와 findByStudy_Id 둘의 쿼리는 위와 동일하게 나갑니다.

그렇다면 왜 _ 을 붙여서 네이밍을 해야할까?

궁금해서 이에 대한 답도 찾아봤습니다.

이슈에 작성한 내용에서 말했듯이 JPA에서 외래키를 가진 엔티티를 조회할 때, _를 붙이는 네이밍 규칙이 있습니다.
예를 들어, StudyMember 엔티티에서 study 필드가 외래키를 가지고 있다면, 해당 필드의 이름은 study_id로 작성해야 합니다.
이렇게 함으로써, JPA는 자동으로 외래키를 찾아 매핑하는 과정을 수행할 수 있습니다.

findByStudyId 메서드또한 StudyMember 엔티티에서 study_id 필드를 조회하는 방법입니다.
하지만, 필드명과 외래키 컬럼명이 일치하지 않는 경우에는, @JoinColumn 어노테이션을 사용하여 직접 매핑 정보를 지정해주어야 합니다. 따라서, _를 포함하는 네이밍 규칙을 지키는 것이 좋습니다. 이렇게 함으로써, 코딩 컨벤션을 일관성 있게 유지할 수 있으며, 가독성도 높아집니다.


studyMembers.forEach(studyMember ->
assignmentMemberRepository.save(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.SortedMap;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
Expand Down Expand Up @@ -127,7 +126,7 @@ public StudiesResponse find(Long memberId, StudyConditionRequest studyConditionR

List<Study> studies = studyRepository.findAll();
List<StudyResponse> studyResponses = studies.stream().map(study -> {
Integer memberCount = studyMemberRepository.countStudyMemberByStudyId(study.getId());
Integer memberCount = studyMemberRepository.countStudyMemberByStudy_Id(study.getId());
return new StudyResponse(
study.getId(),
study.getTitle(),
Expand Down Expand Up @@ -196,7 +195,7 @@ public StudyDetailResponse findById(Long memberId, Long studyId) {
public StudyPreviewsResponse findPreview(Long memberId, StudyPreviewConditionRequest studyPreviewConditionRequest) {
log.debug("[스터디 미리보기 조회] memberId = {}, StudyPreviewConditionRequest = {}", memberId, studyPreviewConditionRequest);

List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByMemberId(memberId);
List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByMember_Id(memberId);
List<String> memberProfiles = new ArrayList<>();

if (studyPreviewConditionRequest.getType().equals(StudyPreviewType.MY)) {
Expand Down Expand Up @@ -225,7 +224,7 @@ public StudyPreviewsResponse findPreview(Long memberId, StudyPreviewConditionReq
List<Study> studies = studyRepository.findAll(Sort.by(Direction.DESC, "createdAt"));
List<StudyPreviewResponse> randomStudyPreviewResponse = studies.stream().map(study -> {

List<StudyMember> members = studyMemberRepository.findStudyMembersByStudyId(study.getId());
List<StudyMember> members = studyMemberRepository.findStudyMembersByStudy_Id(study.getId());

memberProfiles.clear();
for (StudyMember member : members) {
Expand Down Expand Up @@ -312,7 +311,7 @@ public StudyDetailResponse modify(Long memberId, Long studyId, StudyRequest stud
public void delete(Long memberId, Long studyId) {
log.debug("[스터디 삭제] studyId = {}", studyId);

StudyMember studyLeader = studyMemberRepository.findStudyMemberByStudyIdAndLeaderIsTrue(studyId);
StudyMember studyLeader = studyMemberRepository.findStudyMemberByStudy_IdAndLeaderIsTrue(studyId);

if (!Objects.equals(studyLeader.getMember().getId(), memberId)) {
throw new NotMatchStudyAndMemberException();
Expand Down Expand Up @@ -351,7 +350,7 @@ private Integer getStudyInterestCount(Study study) {
}

private boolean isStudyInterested(Long loginMemberId, Study study) {
return studyInterestRepository.findByMemberIdAndStudy(loginMemberId, study).isPresent();
return studyInterestRepository.findByMember_IdAndStudy(loginMemberId, study).isPresent();
}

private static boolean leaderCheck(Long loginMemberId, boolean isLeader, StudyMember member) {
Expand All @@ -367,7 +366,7 @@ private Study getStudy(Long studyId) {
}

private List<StudyMember> getStudyMembers(Long studyId) {
return studyMemberRepository.findStudyMembersByStudyId(
return studyMemberRepository.findStudyMembersByStudy_Id(
studyId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public interface StudyInterestRepository extends JpaRepository<StudyInterest, Lo

Integer countByStudyId(Long studyId);

Optional<StudyInterest> findByMemberIdAndStudy(Long memberId, Study study);
Optional<StudyInterest> findByMember_IdAndStudy(Long memberId, Study study);

void deleteByMemberIdAndStudyId(Long memberId, Long studyId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
import com.example.be.core.domain.study.StudyMember;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

public interface StudyMemberRepository extends JpaRepository<StudyMember, Long> {
List<StudyMember> findStudyMembersByStudyId(Long studyId);
List<StudyMember> findStudyMembersByStudy_Id(Long studyId);

List<StudyMember> findStudyMembersByMemberId(Long memberId);
List<StudyMember> findStudyMembersByMember_Id(Long memberId);

StudyMember findStudyMemberByStudyIdAndLeaderIsTrue(Long studyId);
StudyMember findStudyMemberByStudy_IdAndLeaderIsTrue(Long studyId);

Integer countStudyMemberByStudyId(Long studyId);
Integer countStudyMemberByStudy_Id(Long studyId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ private void initStudy() {
*/
private void initAssignment() {
Study study = studyRepository.findById(1L).get();
List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByStudyId(
List<StudyMember> studyMembers = studyMemberRepository.findStudyMembersByStudy_Id(
study.getId());
for (int i = 1; i <= NUMBER_OF_ASSIGNMENT; i++) {
Assignment assignment = assignmentRepository.save(
Expand Down