inblog logo
|
silver
    스프링부트

    [스프링부트 blogV1] 18. 게시글 수정하기

    silver's avatar
    silver
    Dec 30, 2024
    [스프링부트 blogV1] 18. 게시글 수정하기
    Contents
    1. Repository2. Controller3. Service

    1. Repository

    public void update(int id, String title, String content) { Query q = em.createNativeQuery("update board_tb set title = ?, content = ? where id = ?"); q.setParameter(1, title); q.setParameter(2, content); q.setParameter(3, id); q.executeUpdate(); }

    2. Controller

    @PostMapping("/board/{id}/update") public String update(@PathVariable("id") int id,BoardRequest.UpdateDTO updateDTO) { boardService.게시글수정하기(id,updateDTO.getTitle(),updateDTO.getContent()); return "redirect:/board/"+id; }
    form으로 받은 parameter들을 하나씩 받고 싶다면 @RequestParam(”title”) String title 이런식으로 받아오면 된다.
    BoardRequest.UpdateDTO updateDTO가 아니라 Board board로 받아도 된다. 이 때, 나머지 id, createdAt은 null 처리가 돼서 null값을 가질 수 없는 int id자리에는 0으로 초기화가 되므로 id는 int가 아닌 Integer로 설정하는 것이 좋다.
    → dto로 관리하는게 편하다

    int와 Integer

    int: 기본 데이터 타입(int, long, float, double…)으로 null 값을 가질 수 없다. 초기화하지 않으면 기본적으로 0으로 초기화된다. Integer: *래퍼 클래스로 int의 객체 표현이다. null 값을 가질 수 있다. 객체이기 때문에 메서드와 속성을 사용할 수 있다. Integer 클래스에는 다양한 유틸리티 메서드가 포함되어 있다.
    notion image
     
    래퍼 클래스(Wrapper Class)는 Java에서 기본 데이터 타입(primitive type)을 객체로 변환하기 위해 제공되는 클래스이다. 기본 데이터 타입은 객체가 아니기 때문에, 객체로서의 기능(예: 메서드 호출, null 값 할당 등)을 사용하려면 래퍼 클래스를 사용해야 한다.
    1. 객체화 : 기본 데이터 타입을 객체로 감싸서 사용할 수 있게 해준다. 예를 들어, int를 Integer로 변환하여 객체로 사용할 수 있다.
    1. null 값: 래퍼 클래스는 null 값을 가질 수 있다. 이는 데이터베이스와의 상호작용이나 컬렉션에서 유용하다.
    1. 유틸리티 메서드: 래퍼 클래스는 다양한 유틸리티 메서드를 제공한다. 예를 들어, Integer 클래스는 숫자를 문자열로 변환하거나, 문자열을 숫자로 변환하는 메서드 등을 제공한다.
    1. 자동 박싱과 언박싱: Java는 자동 박싱(primitive to wrapper)과 자동 언박싱(wrapper to primitive)을 지원한다.
    // 3. 유틸리티 메서드 int num = Integer.parseInt("123"); // 문자열을 int로 변환 String str = Integer.toString(123); // int를 문자열로 변환
    // 4. 자동박싱과 언박싱 Integer integerObj = 10; // 자동 박싱 int primitiveInt = integerObj; // 자동 언박싱
     

    3. Service

    @Transactional public void 게시글수정하기(int id, BoardRequest.UpdateDTO updateDTO) { boardRepository.update(id,updateDTO.getTitle(),updateDTO.getContent()); }
    Repository의 update를 다른 Service의 메서드가 사용할 수도 있다 -> Repository의 update가 UpdateDTO에 의존되지 않도록 updateDTO.getTitle이런식으로 빼서 Repository로 넘겨준다. Controller와 Service는 1:1 매칭된다. 그래서 종속돼도 됨 -> UpdateDTO 통째로 넘김
    Share article
    Contents
    1. Repository2. Controller3. Service

    silver

    RSS·Powered by Inblog