newcodingtest / ProjectManagementSystem

:sunny::sunny:레거시 코드 리펙토링 해보기:sunny::sunny:
1 stars 0 forks source link

상.하위 작업 조회시 N+1문제 해결 #29

Open newcodingtest opened 2 years ago

newcodingtest commented 2 years ago

Task(상위작업)

Table
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@ToString
@DynamicUpdate
public class Task extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="TASK_ID")
    private Long tid;
    .
    .
    .
    @OneToMany(mappedBy = "task", fetch = FetchType.LAZY, orphanRemoval = true)
    private List<SubTask> subTaskList = new ArrayList<SubTask>();
    .
    .

Global 로딩 전략을 지연로딩으로 설정하였다.

SubTask(하위작업)

@Table
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@ToString(exclude = "task")
@DynamicUpdate
public class SubTask extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="SUB_ID")
    private Long sid;
    .
    .
    .
    @ManyToOne
    private Task task;
    .
    .
}

Repository

@Repository
public interface TaskRepository extends  JpaRepository<Task, Long>, TaskRepositoryCustom{

    @Query("select distinct t from Task t join fetch t.subTaskList where t.tid=:tid ")
    Task getTaskListWithAll(@Param(value = "tid") Long tid);    
}

패치 조인을 적용해서 N+1을 해결하였다.

결과값

image

패치 조인으로 인해서 내가 원하는 조건에 만족하는 inner join이 적용됨을 확인 할 수 있다.

 result=Task(tid=1, taskType=개발, detailedTaskType=개발, divisionOfTask=주 업무, taskContents=test, taskTitle=test, writer=null, remarks=test, taskStartDate=2022-03-31T10:14, taskEndDate=2022-04-14T10:14, realProgress=10.0, savedWeekDate=null, statusCode=진행전, parent=null, reportRegistFlag=1, subTaskList=[SubTask(sid=1, subTitle=테스트용 제목, subContents=테스트용 내용, subStartDate=2022-03-08T10:10, subEndDate=2022-03-08T10:10, subRealProgress=10.0, subReportRegistFlag=1), SubTask(sid=2, subTitle=te, subContents=te, subStartDate=2022-04-07T13:11, subEndDate=2022-04-07T13:11, subRealProgress=0.0, subReportRegistFlag=0), SubTask(sid=3, subTitle=te, subContents=te, subStartDate=2022-04-07T13:11, subEndDate=2022-04-07T13:11, subRealProgress=0.0, subReportRegistFlag=0), SubTask(sid=4, subTitle=te, subContents=te, subStartDate=2022-04-07T13:11, subEndDate=2022-04-07T13:11, subRealProgress=0.0, subReportRegistFlag=0), SubTask(sid=5, subTitle=te1, subContents=, subStartDate=2022-04-06T13:12, subEndDate=2022-04-06T13:12, subRealProgress=0.0, subReportRegistFlag=0), SubTask(sid=6, subTitle=첫번째제목, subContents=첫번째내용, subStartDate=2022-03-08T10:10, subEndDate=2022-03-08T10:10, subRealProgress=0.0, subReportRegistFlag=0), SubTask(sid=7, subTitle=두번째제목, subContents=두번째내용, subStartDate=2022-03-08T10:10, subEndDate=2022-03-08T10:10, subRealProgress=0.0, subReportRegistFlag=1)], projectId=null)