본문 바로가기
Sketcher

FullCalendar 와 DB 연동하기 -5 (조회, 수정, 삭제 Controller & Service)

by 완두완두콩 2022. 3. 2.

 

처음 FullCalendar 구현할 때는 확확 다이나믹하게 바뀌어서

만드는 재미가 있었는데 점점 세부적인 부분으로 들어가다보니 

재미가 없어지는 중...이지만 구현을 해보자!..

 

저번 포스팅에서는 생성 기능만 작성했는데 이번에는 조회, 수정, 삭제에 대해

작성해보고자 한다.

 

문제점

 

우선 조회의 경우, 생성 로직을 만들다보니 아예 작동이 안됐었다.

data 를 넘기는 부분에는 문제가 없었으므로 Controller를 수정함으로써 간단하게 해결!

 

수정 & 삭제는 둘 다 Controller 코드가 엉망이였다.

이를 처음부터 다시 뜯어고치고, Service, Repository 부분을 추가 & 수정했다.

 

(우선 구현한 부분을 자랑)

 

 

HTML

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/menu_layout}">
<head>
    <title>스케줄 수정</title>
    <link th:href="@{/css/manager_list.css}" rel="stylesheet"/>
    <!-- jquery CDN -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- fullcalendar CDN -->
    <link href='https://cdn.jsdelivr.net/npm/fullcalendar@5.8.0/main.min.css' rel='stylesheet'/>
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@5.8.0/main.min.js'></script>
    <!-- fullcalendar 언어 CDN -->
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@5.8.0/locales-all.min.js'></script>
    <script>
 
        var calendar = null;
        var initialLocaleCode = 'ko';
        var localeSelectorEl = document.getElementById('locale-selector');
 
            $(document).ready(function (){
 
                $(function () {
                    var request = $.ajax({
                        url: "/full-calendar/calendar-admin-update"// 변경하기
                        method: "GET",
                        dataType: "json"
                    });
                    request.done(function (data) {
                        console.log(data); // log 로 데이터 찍어주기.
                        var calendarEl = document.getElementById('calendar');
                        calendar = new FullCalendar.Calendar(calendarEl, {
                            initialDate: '2022-02-07',
                            initialView: 'timeGridWeek',
                            headerToolbar: {
                                left: 'prev,next today',
                                center: 'title',
                                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
                            },
                            navLinks: true,
                            editable: true,
                            selectable: true,
                            droppable: true// this allows things to be dropped onto the calendar
 
                            // eventAdd: function () { // 이벤트가 추가되면 발생하는 이벤트
                            //     // console.log()
                            // },
 
                        /**
                         * 드래그로 이벤트 수정하기
                         */
                        eventDrop: function (info){
 
                            if(confirm("'"+ info.event.title +"' 매니저의 일정을 수정하시겠습니까 ?")){
 
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                            var obj = new Object();
 
                            obj.title = info.event._def.title;
                            obj.start = info.event._instance.range.start;
                            obj.end = info.event._instance.range.end;
 
                            obj.oldTitle = info.oldEvent._def.title;
                            obj.oldStart = info.oldEvent._instance.range.start;
                            obj.oldEnd = info.oldEvent._instance.range.end;
 
                            events.push(obj);
 
                            console.log(events);
                            }else{
                                // Get 방식으로 데이터를 조회해서 가져와야하는데 새로고침 하지 않고는 어떻게
                                // 해야할지 감이 안잡혀서 우선 reload 방식으로..
                                location.reload();
                            }
                            $(function modifyData() {
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "PATCH",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                            })
 
 
                        },
                            eventResize: function (info){
                                console.log(info);
                                if(confirm("'"+ info.event.title +"' 매니저의 일정을 수정하시겠습니까 ?")){
 
                                var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                                var obj = new Object();
 
                                obj.title = info.event._def.title;
                                obj.start = info.event._instance.range.start;
                                obj.end = info.event._instance.range.end;
 
                                obj.oldTitle = info.oldEvent._def.title;
                                obj.oldStart = info.oldEvent._instance.range.start;
                                obj.oldEnd = info.oldEvent._instance.range.end;
 
                                events.push(obj);
 
                                console.log(events);
                                }else{
                                    location.reload();
                                }
                                $(function modifyData() {
                                    $.ajax({
                                        url: "/full-calendar/calendar-admin-update",
                                        method: "PATCH",
                                        dataType: "json",
                                        data: JSON.stringify(events),
                                        contentType: 'application/json',
                                    })
                                })
                            },
 
                        /**
                         * 드래그로 이벤트 추가하기
                         * 이름 다른 경우 표현 안돼야 하는데 어떻게 해야할까?..
                         */
                        select: function (arg) { // 캘린더에서 이벤트를 생성할 수 있다.
 
                            var title = prompt('매니저 이름을 입력해주세요.');
                            if (title) {
                                calendar.addEvent({
                                    title: title,
                                    start: arg.start,
                                    end: arg.end,
                                    allDay: arg.allDay
                                })
                            }
 
                            console.log(arg);
 
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                                var obj = new Object();     // Json 을 담기 위해 Object 선언
 
                                obj.title = title; // 이벤트 명칭  ConsoleLog 로 확인 가능.
                                obj.start = arg.start; // 시작
                                obj.end = arg.end; // 끝
                                events.push(obj);
                            var jsondata = JSON.stringify(events);
                            console.log(jsondata);
 
 
                            $(function saveData(jsondata) {
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "POST",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                                    // .done(function (events) {
                                    //     // alert(events);
                                    // })
                                    // .fail(function (request, status, error) {
                                    //      // alert("에러 발생" + error);
                                    // });
                                calendar.unselect()
                            });
                        },
 
                        /**
                         * 이벤트 선택해서 삭제하기
                         */
                        eventClick: function (info){
                            if(confirm("'"+ info.event.title +"' 매니저의 일정을 삭제하시겠습니까 ?")){
                                // 확인 클릭 시
                                info.event.remove();
 
 
                            console.log(info.event);
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                            var obj = new Object();
                                obj.title = info.event._def.title;
                                obj.start = info.event._instance.range.start;
                                obj.end = info.event._instance.range.end;
                                events.push(obj);
 
                            console.log(events);
                            }
                            $(function deleteData(){
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "DELETE",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                            })
                        },
                            locale: 'ko',
                            // eventRemove: function (obj) { // 이벤트가 삭제되면 발생하는 이벤트
                        //
                        // },
                            events: data
                        });
                        calendar.render();
                    });
 
                    });
 
        });
 
 
 
 
    </script>
    <style>
        body {
            font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
            font-size: 14px;
        }
 
        table {
            text-align: left;
        }
 
        .access_user {
            width: 300px;
            height: 100px;
            float: right;
            margin-right: 100px;
            padding-top: 50px;
        }
 
        #external-events {
            position: absolute;
            /*left: 100 px;*/
            /*top: 100px;*/
            width: 150px;
            overflow: hidden;
            padding: 0 10px;
            margin-top: 80px;
            border: 1px solid #ccc;
            background: #eee;
            text-align: left;
        }
 
        #external-events h4 {
            font-size: 16px;
            margin-top: 0;
            padding-top: 1em;
        }
 
        #external-events .fc-event {
            margin: 3px 0;
            cursor: move;
        }
 
        #external-events p {
            margin: 1.5em 0;
            font-size: 11px;
            color: #666;
        }
 
        #external-events p input {
            margin: 0;
            vertical-align: middle;
        }
 
        #calendar-wrap {
            margin-left: 200px;
        }
 
        #calendar {
            max-width: 1100px;
            margin: 40px auto;
            padding: 0 10px;
        }
    </style>
 
</head>
 
<th:block layout:fragment="ground-wrap">
    <div class="ground">
        <div class="main">
            <div class="title1">
                <h1>스케줄 수정</h1>
            </div>
                <div id='calendar-wrap'>
                    <div id='calendar'></div>
                </div>
            </div>
        </div>
    </div>
 
    <script src="fullcalendar/lib/locales-all.js"></script>
 
    <script>
        var calendarEl = document.getElementById('calendar');
 
        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: ["dayGrid"]
            , locale: "ko"
        });
 
    </script>
 
    <script>
        // 기본 위치(top)값
        var floatPosition = parseInt($("#external-events").css('top'))
 
        // scroll 인식
        $(window).scroll(function () {
            // 현재 스크롤 위치
            var currentTop = $(window).scrollTop();
            var bannerTop = currentTop + floatPosition + "px";
 
            //이동 애니메이션
            $("#external-events").stop().animate({
                "top": bannerTop
            }, 500);
        }).scroll();
    </script>
</th:block>
</html>
cs

 

전체 HTML 코드이다!

사실 저번과 크게 달라진 점은 없고, 수정 버튼을 눌렀을 때 뜬 팝업에서

취소를 누르는 경우에도 스케줄이 이동하는 현상이 있어서 

location.reload()로 다시 데이터를 받아오는 방식으로 바꾸었다.

바로 렌더링 되는 방식을 구현해보면 좋을 것 같은데 어떻게 구현해야 할지

아직은 고민중이다!.. 우선은 임시 방편으로..

 

Controller

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package sketcher.scheduling.controller;
 
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.jni.Local;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import sketcher.scheduling.domain.ManagerAssignSchedule;
import sketcher.scheduling.domain.Schedule;
import sketcher.scheduling.domain.User;
import sketcher.scheduling.dto.ManagerAssignScheduleDto;
import sketcher.scheduling.dto.ScheduleDto;
import sketcher.scheduling.dto.UserDto;
import sketcher.scheduling.repository.ScheduleRepository;
import sketcher.scheduling.repository.UserRepository;
import sketcher.scheduling.service.ManagerAssignScheduleService;
import sketcher.scheduling.service.ScheduleService;
import sketcher.scheduling.service.UserService;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
 
@Controller
@RequiredArgsConstructor
@RequestMapping("/full-calendar")
public class CalendarController {
    
 
    private final ScheduleService scheduleService;
    private final ScheduleRepository scheduleRepository;
    private final ManagerAssignScheduleService managerAssignScheduleService;
    private final UserService userService;
    private final UserRepository userRepository;
 
    /**
     * calendar-admin 페이지 조회
     */
    @GetMapping("/calendar-admin")
    @ResponseBody
    public List<Map<String, Object>> showAllEvent() throws Exception {
 
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArr = new JSONArray();
 
        HashMap<String, Object> hash = new HashMap<>();
 
        List<Schedule> list = scheduleService.findAll();
 
        for (Schedule schedule : list) {
            hash.put("title", schedule.getCreator_id());
            hash.put("start", schedule.getScheduleDateTimeStart());
            hash.put("end", schedule.getScheduleDateTimeEnd());
 
            jsonObj = new JSONObject(hash);
            jsonArr.add(jsonObj);
        }
        log.info("jsonArrCheck: {}", jsonArr);
        return jsonArr;
    }
 
    /**
     * calendar-admin-update 페이지 조회
     */
    @GetMapping("/calendar-admin-update")
    @ResponseBody
    public List<Map<String, Object>> showAllEventInUpdate() throws Exception {
 
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArr = new JSONArray();
 
        HashMap<String, Object> hash = new HashMap<>();
 
        List<Schedule> list = scheduleService.findAll();
 
        for (Schedule schedule : list) {
            hash.put("title", schedule.getCreator_id());
            hash.put("start", schedule.getScheduleDateTimeStart());
            hash.put("end", schedule.getScheduleDateTimeEnd());
 
            jsonObj = new JSONObject(hash);
            jsonArr.add(jsonObj);
        }
        log.info("jsonArrCheck: {}", jsonArr);
        return jsonArr;
    }
    
    /**
     * calendar-admin-update 페이지 이벤트 생성
     */
    @PostMapping("/calendar-admin-update")
    @ResponseBody
    public String addEvent(@RequestBody List<Map<String, Object>> param) throws Exception {
 
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.KOREA);
 
        for (Map<String, Object> list : param) {
 
            String eventName = (String) list.get("title"); // 이름 받아오기
            String startDateString = (String) list.get("start");
            String endDateString = (String) list.get("end");
 
            LocalDateTime startDateUTC = LocalDateTime.parse(startDateString, dateTimeFormatter);
            LocalDateTime endDateUTC = LocalDateTime.parse(endDateString, dateTimeFormatter);
 
            LocalDateTime startDate = startDateUTC.plusHours(9);
            LocalDateTime endDate = endDateUTC.plusHours(9);
 
            User user = userService.findByUsername(eventName).get();
            String username = user.getUsername();
 
 
            System.out.println("=================================");
            System.out.println("startDate = " + startDate);
            /**
             * exception 처리를 통해 존재하지 않는 경우 alert 필요
             */
            System.out.println("username = " + username);
            System.out.println("eventName = " + eventName);
 
            if (eventName.equals(username)) {
                ScheduleDto scheduleDto = ScheduleDto.builder()
                        .creator_id(eventName)
                        .scheduleDateTimeStart(startDate)
                        .scheduleDateTimeEnd(endDate)
                        .build();
 
                Integer scheduleId = scheduleService.saveSchedule(scheduleDto);
                Schedule scheduleEntity = scheduleService.findById(scheduleId).get();
 
                ManagerAssignScheduleDto managerAssignScheduleDto = ManagerAssignScheduleDto.builder()
                        .user(user)
                        .schedule(scheduleEntity)
                        .build();
 
                managerAssignScheduleService.saveManagerAssignSchedule(managerAssignScheduleDto);
            }
        }
        return "/full-calendar/calendar-admin-update";
    }
 
    /**
     * calendar-admin-update 페이지 이벤트 삭제
     */
    @DeleteMapping("/calendar-admin-update")
    @ResponseBody
    public String deleteEvent(@RequestBody List<Map<String, Object>> param) {
 
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.KOREA);
 
        for (Map<String, Object> list : param) {
 
            System.out.println("list = " + list);
 
            String eventName = (String) list.get("title"); // 이름 받아오기
            String startDateString = (String) list.get("start");
            String endDateString = (String) list.get("end");
 
            System.out.println("startDateString = " + startDateString);
 
            LocalDateTime startDate = LocalDateTime.parse(startDateString, dateTimeFormatter);
            LocalDateTime endDate = LocalDateTime.parse(endDateString, dateTimeFormatter);
 
            System.out.println("startDate = " + startDate);
 
            User user = userService.findByUsername(eventName).get();
            String username = user.getUsername();
 
//            Optional<Schedule> schedules = scheduleService.findByScheduleDateTimeStart(startDate);
            Schedule schedule = scheduleService.findByScheduleDateTimeStartAndScheduleDateTimeEnd(startDate, endDate).get();
            Integer scheduleId = schedule.getId();
            System.out.println("=================================");
            System.out.println("scheduleId = " + scheduleId);
 
            ManagerAssignSchedule assignSchedule = managerAssignScheduleService.findBySchedule(schedule).get();
            Integer assignScheduleId = assignSchedule.getId();
            System.out.println("========================");
            System.out.println("assignSchedule = " + assignSchedule);
            System.out.println("assignScheduleId = " + assignScheduleId);
 
            /**
             * exception 처리를 통해 존재하지 않는 경우 alert 필요
             */
 
            if (eventName.equals(username)) {
//                System.out.println("success");
//                scheduleService.deleteById(scheduleId);
//                managerAssignScheduleService.deleteById(assignScheduleId);
                managerAssignScheduleService.deleteBySchedule(schedule);
            }
        }
        return "/full-calendar/calendar-admin-update";
    }
 
    /**
     * 취소를 누름에도 데이터 파싱. 체크해서 없애기.
     */
    /**
     * calendar-admin-update 페이지 이벤트 생성
     */
    @PatchMapping("/calendar-admin-update")
    @ResponseBody
    public String modifyEvent(@RequestBody List<Map<String, Object>> param) {
 
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.KOREA);
 
 
        for (Map<String, Object> list : param) {
 
            String eventName = (String) list.get("title"); // 이름 받아오기
            String startDateString = (String) list.get("start");
            String endDateString = (String) list.get("end");
 
            String oldTitle = (String) list.get("oldTitle");
            String oldStartString = (String) list.get("oldStart");
            String oldEndString = (String) list.get("oldEnd");
 
            LocalDateTime modifiedStartDate = LocalDateTime.parse(startDateString, dateTimeFormatter);
            LocalDateTime modifiedEndDate = LocalDateTime.parse(endDateString, dateTimeFormatter);
            LocalDateTime oldStart = LocalDateTime.parse(oldStartString, dateTimeFormatter);
            LocalDateTime oldEnd = LocalDateTime.parse(oldEndString, dateTimeFormatter);
 
            System.out.println("=====================================");
            System.out.println("modifiedStartDate = " + modifiedStartDate);
            System.out.println("modifiedEndDate = " + modifiedEndDate);
            System.out.println("oldTitle = " + oldTitle);
            System.out.println("oldStart = " + oldStart);
            System.out.println("oldEnd = " + oldEnd);
 
            Schedule schedule = scheduleService.findByScheduleDateTimeStartAndScheduleDateTimeEnd(oldStart, oldEnd).get();
            Integer scheduleId = schedule.getId();
 
 
            System.out.println("=====================================");
            System.out.println("scheduleId = " + scheduleId);
            if (scheduleId != null) {
 
                ScheduleDto scheduleDto = ScheduleDto.builder()
                        .scheduleDateTimeStart(modifiedStartDate)
                        .scheduleDateTimeEnd(modifiedEndDate)
                        .build();
 
                scheduleService.update(scheduleId, scheduleDto);
            }
        }
        return "/full-calendar/calendar-admin-update";
    }
}
 
cs

조회 부분은 이전과 동일하다.

다만 calendar-admin-update 페이지에도 Get 방식으로 데이터를 가져와서

이벤트를 조회할 수 있도록 추가했다.

 

바뀐 부분은 삭제 , 수정 부분인데

 

삭제의 경우 , 스케줄 시작 - 끝나는 시간이 같은 스케줄을 찾아내서

해당 스케줄을 삭제하는 로직을 만들었다.

 

저 부분도 수정이 필요한데, creator_id 속성을 추가하여 id 까지 같은 경우

데이터를 뽑아오는 방식으로 처리하면 될 것 같다.

 

삭제를 하는 경우, assgin 테이블과 schedule 테이블 둘 다 삭제해야 하는데

Foreign Key 때문에 하나의 트랜잭션이 아니면 삭제가 되지 않아서 

오류가 발생했었다.

 

처음에는 그냥 Controller 부분에 Transactional 어노테이션을 붙여서 해결했었는데

트랜잭션은 항상 Service 영역에서 처리해야 한다는 글을 읽고,

Service 내의 하나의 트랜잭션에서 assign 과 Schedule

을 한번에 삭제 하는 방식으로 변경했다.

 

다행히 Controller 에서 트랜잭션 어노테이션을 빼도 정상 작동함을 확인했다!

 

수정의 경우 , 변경된 값인 title, start, end 값을 가져오고 

변경되기 전의 값인 oldTitle, oldStart, oldEnd 값을 가져와서 

수정에서의 로직과 동일하게 start-end 시간이 같은 값을 가져와서 

수정하는 방식으로 작성했다.

 

이 부분도 creator_id 를 추가하여 이름,시작시간,끝나는 시간 모두 동일한

데이터 값을 가져와서 수정하는 방식으로 변경해야 한다!

(테이블 관련 설계에서 조금 애매한 부분이 있어서 일단은 이렇게만 작성했다!)

 

Service

 

1
2
3
4
5
6
7
    @Transactional
    public Integer deleteBySchedule(Schedule schedule){
        Schedule schedule1 = scheduleRepository.findById(schedule.getId()).get();
        managerAssignScheduleRepository.deleteBySchedule(schedule1);
        scheduleRepository.deleteById(schedule1.getId());
        return schedule1.getId();
    }
cs

현재 작성된 모든 부분들은 JPA 인터페이스로 구현을 해서 특별히 언급할만한 내용은

삭제와 수정 로직이다.

 

삭제는 앞에서 말했듯, 두개의 테이블에서 데이터를 삭제하는 경우 

Foreign Key 때문에 하나의 트랜잭션에서 삭제를 진행해야 한다.

그 코드는 위와 같다!

1
2
3
4
    public void update(LocalDateTime scheduleDateTimeStart,LocalDateTime scheduleDateTimeEnd){
        this.scheduleDateTimeStart = scheduleDateTimeStart;
        this.scheduleDateTimeEnd = scheduleDateTimeEnd;
    }
cs
1
2
3
4
5
6
7
    @Transactional
    public void update(Integer id, ScheduleDto dto){
        Schedule schedule = scheduleRepository.findById(id).orElseThrow(() ->
                new IllegalArgumentException("해당 스케줄이 없습니다. " + id));
 
            schedule.update(dto.getScheduleDateTimeStart(), dto.getScheduleDateTimeEnd());
    }
cs

JPA 에서는 더티체킹을 이용해서 수정을 진행한다.

더티체킹은 영속성 컨텍스트 내에 있는 데이터를 기준으로, 기존의 값이 다른 값으로 바뀌면

따로 update 쿼리를 짜주지 않아도 알아서 변경을 감지하고 값을 변경해준다.

 

다음과 같이 update 구문을 날리면 findById 구문을 통해 영속성 컨텍스트에 값이 들어가고

바뀐 값을 조회해서 변경하게 된다.

 

+ 한글화 작업도 완료했다! 간단히 locale: 'ko' 를 넣음으로 해결했다.

 

추가로 구현해야 하는 부분

 

※ 생성에서 USER 테이블에 없는 아이디를 입력하면,

DB 에 값이 파싱되지는 않지만 UI 에는 표현되고 있다. (새로 고침하면 해결)

이 부분을 어떻게 해결해야 할까 고민..(똑같이 location.reload로 할까 고민중) -> 수정도 동일 고민

 

※ 이벤트 색상이 모두 동일한데 이 부분을 어떻게 해결해야 할지

전혀 감이 안잡힌다.. 가장 큰 문제!..

 

※ ApplicationRunner 클래스를 만들어서 초기 user 값을 집어넣고 테스트를 진행중인데

해당 클래스를 삭제하면 아예 작동이 안되는 오류가 발생중이다

뭐가 문제인지 한번 찾아봐야 할 것 같다.

 

느낀점

코드를 짜긴 했지만 좋은 코드가 아닌 느낌이 팍팍 든다.

마치 아기돼지삼형제에서 첫째 돼지가 만든 집같다..

늑대의 콧바람 한방에 날아가는 집같은 느낌..

공부하면서 차차 나아지겠지 라는 생각..

 

다음편 ! 

https://dodokong.tistory.com/48?category=1262083

 

FullCalendar 와 DB 연동하기 -6 (코드 수정 & 매니저별 조회)

이전의 포스팅들에서 뭔가 테이블 설계가 이상하다.. 쿼리문이 이상해.. 했었는데 다행히 회의에서 팀원들의 명석한 두뇌로 테이블을 대폭 수정했다. 테이블 수정하면서 기존 코드를 이것저것

dodokong.tistory.com

 

댓글