개발공부
[ JPA ] QueryDSL Select에 DTO 사용하는 경우 자동 조인
ironprayer
2023. 5. 21. 23:00
QueryDSL 자동 조인
QueryDSL를 사용할 때 조인 메서드를 사용하지 않았도 Eentity에 JoinColumn이 걸려있는 다른 객체의 필드를 사용할 때 자동 조인이 발생한다. 아래 예시의 경우는 ManitoMapping과 User(manito) Entity와 조인을 하지 않았음에도 자동 조인이 된다.
1. QueryDSL이 작성된 코드
public GroupMappingDTO findGroupMapping(Long groupId, Long userId) {
return queryFactory
.select(new QGroupMappingDTO(
manitoMapping.user.id,
manitoMapping.manito.id,
// 자동 조인이 되는 부분 ...
manitoMapping.manito.name,
// ... 자동 조인이 되는 부분
manitoMapping.result)
)
.from(manitoMapping)
.where(manitoMapping.manitoGroup.status.eq(status))
.where(manitoMapping.user.id.eq(userId))
.fetchOne();
}
2. manitoMapping Entity
public class ManitoMapping {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "groupId")
private ManitoGroup manitoGroup;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "manitoId")
private User manito;
@Enumerated(EnumType.STRING)
private ManitoResultStatus result;
}
3. User Eentity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userId;
private String password;
private String name;
private String nickName;
public boolean isMatchedPassword(String password){
return password.equals(this.password);
}
}
결론
자동조인이 되기 때문에 그것을 그대로 사용하는 것이 좋은 것인지 모르겠다. QueryDSL를 사용함에 있어서 내가 의도하지 않은 일이 발생한 것이기 때문이다. 하지만 QueryDSL에 종속되어 있는 상황이기에 어쩔 수 없는 것 같기도 하다.