본문 바로가기
스프링

API에 원하는 컬럼만 추려서 반환하는 방법

by 리포터12 2022. 12. 21.
728x90

1. 엔티티 클래스 작성

@Getter
@Entity
@NoArgsConstructor
public class Board extends TimeStamp {
    // 제목, 작성자명, 작성 내용, 작성 날짜를 조회하기
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;
    @Column(nullable = false)
    private String writer;
    @Column(nullable = false)
    private String content;
    @Column(nullable = false)
    private String password;
    //작성 날짜는 상속 받아 처리함.

    public Board(BoardRequest boardRequest) {
        this.title = boardRequest.getTitle();
        this.writer = boardRequest.getWriter();
        this.password = boardRequest.getPassword();
        this.content = boardRequest.getContent();
    }
}

2. password 등의 민감정보 제외하고 반환하기

...

어떻게?

하나. 원하는 컬럼을 조회하는 getter 메서드 작성하기. 인터페이스로 작성한다.

public interface BoardListMapping {

    public String getTitle();
    public String getWriter();
    public String fofoContent();	// get형식 않았더니 조회가 안 된다. 명백히 규칙이 존재한다.
}

 

둘. JpaRepository를 상속받은 Interface에 다음과 같이 메서드를 선언한다.

public interface BoardRepository extends JpaRepository<Board, Long> {
    List<BoardListMapping> findAllBy();

}

 

이렇게 해두면 repository에서 값을 꺼내와 해당 칼럼들 값만 보여준다.

 

음... findAllby 라던가 여러 추천 메서드명이 나오는데 왜 뜨는지 아직 잘 모르겠다.

 

어떻게 움직이는걸까...

 

 

728x90

'스프링' 카테고리의 다른 글

영속성 컨텍스트(Persistence Context)  (0) 2022.12.23
콘솔 sql 가독성 살리기  (0) 2022.12.22
Bean 등록하기  (0) 2022.12.19
컴포넌트 스캔 & DI(Dependency Injection)  (0) 2022.12.19
@ResponseBody  (0) 2022.12.19

댓글