• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Member 조회시 team_id값 조건걸기

22.01.08 01:43 작성 조회수 219

0

안녕하세요. 수업듣다가 궁금한게 있어 테스트 하다가 막하셔 질문드립니다!

Member 에서

@ManyToOne

@JoinColumn(name = "team_id")

private Team team;

Member N : 1 Team 매핑을 걸게되는데

Member table에서 team_id를 조건부로 걸고

조회하려면 어떻게 해야할까요?

repository에서

List<Team> findAllByTeam_id(Long id);

위쿼리는 entity에서 team_id를 찾지 못해 에러가 뜨는 것 같고..

@Query("select m from Member m where m.team_id = :team_id")

List<Team> findAllByTeam(@Param("team_id") Long id);

이렇게 쿼리를 걸어줘도 m.team_id를 찾지 못하는것 같습니다.. 혹시 Team entity에 걸려있는 @OneToMany를 활용해 조회해야할까요?

그렇다면 member entity가 비어있는 상태에서 team데이터만 있을 때 db에 있는 member를 가져와서 조인해주고 조건을 걸어야 할까요..?

결론적으로.. 심플하게 Member table 에서 team_id = 3 과같은 조건으로 조회하는 방법이 궁금합니다!

답변 1

답변을 작성해보세요.

0

David님의 프로필

David

2022.01.08

안녕하세요. xohoon님, 공식 서포터즈 David입니다.

.
연관관계 매핑만 잘 하셨다면 문제없이 조회되어야 정상입니다.

1. 멤버와 팀 둘 다 잘 저장되었는지 확인해주세요.

2. 팀쪽 연관관계 매핑이 어떻게 되어있는지 확인해주세요.

 

오류가 발생하셨다면 오류 내용도 함께 올려주시면 더욱 정확한 답변을 제공할 수 있습니다.
.
감사합니다.

xohoon님의 프로필

xohoon

2022.01.10

// A table
@Entity public class
A {
@Id @GeneratedValue
@Column(name="a_id")
private Long id; }
// B table
@Entity public class
B {

@Id
@GeneratedValue
@Column(name = "b_id")
private Long id;
/*
* A table 1 : 1 B table
* */
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id")
private A a;
}
// C table
@Entity public class
C {
@Id @GeneratedValue
@Column(name = "c_id")
private Long id;

/*
* B table 1 : N C table
* */
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "b_id")
private B b;
}

위 a, b, c table 이 있습니다.

a와 b 는 1:1 매핑되어있고

b와 c는 1:N 매핑이 되어있습니다.

이때

B Repository에서

a_id 로 B 조회시는 잘 되는데

B findByA_id(Long id);

C Repository에서

b_id로 C 리스트 조회에서 에러가 뜹니다..

List<C> findAllByB_id(Long id);

B_id를 찾을 수 없다는데..

에러를 찾아보면 entity에 b_id를 bId 카멜표기법으로 바꾸면 된다는데

보시다시피 entity에 b_id를 가지고 있지 않습니다.

또한 a_id도 못찾으면 이해를 하겠으나 a_id는 잘 찾아서 조회합니다..

 

@Entity, @Service, @Transactional 적용되어있습니다..

 

error message : 

Error creating bean with name 'cService' defined in file []: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException:

Error creating bean with name 'cRepository' defined in CRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:

Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List CRepository.findAllByB_id(java.lang.Long)!

Reason: Failed to create query for method public abstract java.util.List CRepository.findAllByB_id(java.lang.Long)! No property com found for type Task!;

nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List CRepository.findAllByB_id(java.lang.Long)! No property com found for type Task!

 

답변 감사합니다

David님의 프로필

David

2022.01.10

동일하게 코드 작성해서 돌렸는데, 잘 동작하네요.

정확한 분석을 위해
전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.
구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

주의: 업로드시 권한 문제 꼭 확인해주세요

추가로 다음 내용도 코멘트 부탁드립니다.

1. 실행 방법을 알려주세요.
2. 어떻게 문제를 확인할 수 있는지 자세한 설명을 남겨주세요.

감사합니다

xohoon님의 프로필

xohoon

2022.01.10

답변 정말 감사합니다.

저도 테스트코드를 따로 작성해서 돌려보았더니 잘 동작했습니다.

하지만 진행중인 토이프로젝트에서는 잘 동작하지않아서.. 도저히 에러를 못잡아서

코드주소를 남겨드립니다..

 

프로젝트 링크 :  https://drive.google.com/file/d/1ohA1Hvk6Bs9XdxnfuhiGIKrrKLLc6_hu/view?usp=sharing

1. 실행방법 : properties 디비설정 후 spring boot 실행 가능한 ide로 실행시키면 될 것 같습니다.

본 프로젝트는 intellij로 진행했습니다.

2. 실행하자마자 아래와 같은 에러가 뜰 것 같습니다.

TaskRepository 에 List<Task> findAllByCom_id(Long id); <- 이부분이 문제인것같습니다.

TaskDetailRepository 에 TaskDetail findByTd_id(Long td_id); <- 이부분 마찬가지로

@Query() 작성안해주면 에러가 납니다..

감사합니다.

 

에러로그 : Error creating bean with name 'companyController' defined in file [/Users/xohoon/workspace/project/devTask/out/production/classes/xohoon/devTask/controller/CompanyController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService' defined in file [/Users/xohoon/workspace/project/devTask/out/production/classes/xohoon/devTask/service/task/TaskService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskRepository' defined in xohoon.devTask.repository.task.TaskRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List xohoon.devTask.repository.task.TaskRepository.findAllByCom_id(java.lang.Long)! Reason: Failed to create query for method public abstract java.util.List xohoon.devTask.repository.task.TaskRepository.findAllByCom_id(java.lang.Long)! No property com found for type Task!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List xohoon.devTask.repository.task.TaskRepository.findAllByCom_id(java.lang.Long)! No property com found for type Task!

David님의 프로필

David

2022.01.10

hibernate에서 변수이름과 컬럼명을 매핑하는 방식과 지정하신 컬럼명과 충돌이 나서 발생하는 문제로 보여지네요. com_id 대신에 company_id로 바꿔서 매핑을 해주세요. joincolumn도 수정해주시고요.

 

xohoon님 죄송하지만 질문 안내에 있는 것처럼 강의내용과 관련된 질문을 올려주시길 부탁드립니다.

마음으로는 상세히 도움을 드리고 싶지만, 하루에도 수 많은 분들이 질문을 올려주십니다. 그래서 강의내용과 관련된 질문에 초점을 맞추는 것이 맞다 생각합니다. 다시 한 번 이해를 부탁드립니다.

xohoon님의 프로필

xohoon

2022.01.11

답변 정말 감사합니다.

아닙니다 제가 죄송합니다 ㅜㅜ 

친절한 답변 감사합니다.