[SpringBoot] 스프링부트 + JPA를 이용한 CRUD 구현 5. 수정 기능 만들기


🎋 Controller


src/main/java/com/test/spring/boot_crud/web/PostsApiController.java

package com.test.spring.boot_crud.web;

import com.test.spring.boot_crud.service.posts.PostsService;
import com.test.spring.boot_crud.web.dto.PostsResponseDto;
import com.test.spring.boot_crud.web.dto.PostsSaveRequestDto;
import com.test.spring.boot_crud.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
public class PostsApiController {

    private final PostsService postsService;

    @PostMapping("/api/posts")
    public Long save(@RequestBody PostsSaveRequestDto requestDto) {
        return postsService.save(requestDto);
    }

    @PutMapping("/api/posts/{id}")
    public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto) {
        return postsService.update(id, requestDto);
    }

    @GetMapping("/api/posts/{id}")
    public PostsResponseDto findById(@PathVariable Long id) {
        return postsService.findById(id);
    }
}



🎋 Dto


src/main/java/com/test/spring/boot_crud/web/dto/PostsResponseDto.java

package com.test.spring.boot_crud.web.dto;

import com.test.spring.boot_crud.domain.posts.Posts;
import lombok.Getter;

@Getter
public class PostsResponseDto {

    private Long id;
    private String title;
    private String author;
    private String content;

    public PostsResponseDto(Posts entity) {
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.author = entity.getAuthor();
        this.content = entity.getContent();
    }
}


src/main/java/com/test/spring/boot_crud/web/dto/PostsUpdateResponseDto.java

package com.test.spring.boot_crud.web.dto;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class PostsUpdateRequestDto {

    private String title;
    private String content;

    @Builder
    public PostsUpdateRequestDto(String title, String content) {
        this.title = title;
        this.content = content;
    }
}



🎋 Domain


src/main/java/com/test/spring/boot_crud/domain/posts/Posts.java

package com.test.spring.boot_crud.domain.posts;

import ...;

@Getter
@NoArgsConstructor
@Entity
public class Posts extends BaseTimeEntity {

    ...

    public void update(String title, String content) {
        this.title = title;
        this.content = content;
    }

}



🎋 Service


src/main/java/com/test/spring/boot_crud/service/posts/PostsService.java

package com.test.spring.boot_crud.service.posts;

import ...

@RequiredArgsConstructor
@Service
public class PostsService {

    ...

    @Transactional
    public Long update(Long id, PostsUpdateRequestDto requestDto) {
        Posts posts = postsRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다."));

        posts.update(requestDto.getTitle(), requestDto.getContent());

        return id;
    }

    public PostsResponseDto findById(Long id) {
        Posts entity = postsRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다."));

        return new PostsResponseDto(entity);
    }
}



🎋 수정 페이지


src/main/resources/templates/posts-update.mustache


<h1>게시글 수정</h1>
<div class="col=md-12">
    <div class="col-md-4">
        <form>
            <div class="form-group">
                <label for="id">번호</label>
                <input type="text" class="form-control" id="id" value="" readonly>
            </div>
            <div class="form-group">
                <label for="title">제목</label>
                <input type="text" class="form-control" id="title" value="">
            </div>
            <div class="form-group">
                <label for="author">작성자</label>
                <input type="text" class="form-control" id="author" value="" readonly>
            </div>
            <div class="form-group">
                <label for="content">내용</label>
                <textarea class="form-control" id="content"></textarea>
            </div>
        </form>
        <a href="/" role="button" class="btn btn-secondary">취소</a>
        <button type="button" class="btn btn-primary" id="btn-update">수정</button>
    </div>
</div>


index.mustache 파일에서 글 제목을 누르면 수정 페이지로 이동하도록 a tag를 추가해주자.

<td><a href="/posts/update/"></a></td>



🎋 js


src/main/resources/static/js/app/index.js

var main = {

    init : function(){
        var _this = this;
        ...
        $('#btn-update').on('click', function(){
            _this.update();
        });
    },

    save : function(){
        ...
        });
    },

    update : function(){
       var data = {
           title: $('#title').val(),
           content: $('#content').val()
       };

       var id = $('#id').val();

       $.ajax({
           type: 'PUT',
           url: '/api/posts/'+id,
           dataType: 'json',
           contentType: 'application/json; charset=utf-8',
           data: JSON.stringify(data)
       }).done(function(){
           alert('글이 수정되었습니다');
           window.location.href= '/';
       }).fail(function (error){
          alert(JSON.stringify(error))
       });
   }
};

main.init();



🎋 Controller


src/main/java/com/test/spring/boot_crud/web/IndexController.java

...
@GetMapping("/posts/update/{id}")
public String postsUpdate(@PathVariable Long id, Model model) {
    PostsResponseDto dto = postsService.findById(id);
    model.addAttribute("post", dto);

    return "posts-update";
}
...



실행해보자!

Categories:

SpringBoot