๐ฐspring data jpa๋ก ๊ณต๋ถํ๋์ค ๋ค์๊ณผ ๊ฐ์ ์ฟผ๋ฆฌ๋ฅผ ์ง๊ณ ๋๋ ค ๋ณด์๋๋ฐ ์๋ฌ๊ฐ ๋ฌ๋ค.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select distinct u.questions from User u join fetch u.questions where u.id = :userid")
List<Question> findQuestionsWith(@Param("userid") Long userid);
}
org.springframework.beans.factory.UnsatisfiedDependencyException
.....
Validation failed for query for method public abstract java.util.List project.blog.repository.UserRepository....!
๋น ์์ฑ๋ถํฐ ์๋ฌ๊ฐ ๋์ ๋ญ๊ฐ ๋ฌธ์ ์ธ์ง ์ถ์๋ค. ๋ก๊ทธ๋ฅผ ๋ณด๋ฉด UserRepository์์ ์๋ฌ๊ฐ ๋ฌ๋ค๊ณ ํ๊ธธ๋ ์ดํด๋ณด์๋ค.
์ ์ฝ๋๋ฅผ ๋ณด๋ฉด user์ Question์ @OneToMany ๊ด๊ณ์ด๊ธฐ์ ์ปฌ๋ ์ ํจ์น๋ฅผ ํ๊ณ ์๋๋ฐ ์ฌ๊ธฐ์ ์๋ฌ๊ฐ ๋ฌ๋ค.
๐ซก๋ฌธ์ ๊ฐ ๋ฐ์ํ ์ด์ ๋ join fetch์ ์์ ๊ฐ์ ธ์จ ์ปฌ๋ ์ ์ select์ ์์ ๋ฐ๋ก ๋ฐํ ํ ์ ์๋๋ฐ ๋๋ ๊ณ์ ์ปฌ๋ ์ ์ ๋ฐํํ๊ณ ์์๊ธฐ ๋๋ฌธ์ด๋ค.
// ์๋ฌ ๋ฐ์
List<Question> questions = em.createQuery("select u.questions from User u join fetch u.questions where u.id = :userid", Question.class).getResultList();
// ์ ์ ์๋
List<User> users = em.createQuery("select u from User u join fetch u.questions where u.id = :userid", User.class).getResultList();
๊ทธ๋์ ์๋์ ๊ฐ์ด ์ฝ๋๋ฅผ ๋ณ๊ฒฝ ํด ์ฃผ๋ ์ ๋๋ก ์๋ํ๋ค.
@Query("select distinct u from User u join fetch u.questions where u.id = :userid")
User findQuestionsWithId(@Param("userid") Long userid);