[JPA] updateQuery Join 지원 안하는 이슈

최성욱·2025년 2월 25일
0

Gathering Class

public class Gathering {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
    private LocalDateTime registerDate;

    @OneToOne(mappedBy = "gathering",fetch = FetchType.LAZY,optional = false)
    private GatheringCount gatheringCount;

 }

GatheringCount class

public class GatheringCount {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @MapsId
    @OneToOne(fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "gathering_id")
    private Gathering gathering;
    private int count;
}

GatheringRepository class

public interface GatheringCountRepository extends JpaRepository<GatheringCount,Long> {

    @Query("update GatheringCount g set g.count = g.count +1 where g.gathering.id =:gatheringId")
    @Modifying
    void addCount(Long gatheringId);

GatheringCountRepository에서 Gathering을 조회할 필요성을 느껴서 서로 Gathering Entity와 GatheringCount Entity사이에 양방향 매핑이 걸려있다. 하지만, Test코드를 작성하는 와중에 Gahtering Entity와 GatheringCount Entity를 세팅하는 메소드를 하게 되며 서로 양방향 매핑이 걸려있어서 작성할 수가 없어서 단방향 매핑으로 전환하기로 하였다.
하지만, sql에 지원되는 join Update Query를 작성할 수 없다. 따라서 SubQuery를 도입하기로 하였다.

public interface GatheringCountRepository extends JpaRepository<GatheringCount,Long> {

    @Query("update GatheringCount gc set gc.count = gc.count+1 " +
            "where gc.id = (select g.id from Gathering g where g.gatheringCount.id = gc.id)")
    @Modifying
    void addCount(Long gatheringId);
   
}
profile
성장을 지향하는 개발자

0개의 댓글