카테고리 없음

spring data jpa 의 @jsonview

머룽 2023. 4. 19. 09:55

spring data jpa 의 jsonview

바로 쓴다.ㅎㅎㅎ 왜냐면 쉬워서 바로 했다. 아무튼 이번엔 @jsonView를 사용해보자 이것도 간단하지만 어노테이션을 많이 추가 해야된다. 그때 그때 맞게 잘 쓰면 될거 같다.
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {

    @Id
    @GeneratedValue
    @Column(name = "account_id")
    @JsonView(View.Accounts.class)
    private Long id;

    @NotNull
    @JsonView(View.Accounts.class)
    private String name;


    @OneToMany(mappedBy = "account")
    private List<Ordered> ordered;
}

class View {
    interface Accounts {}
}

뷰에 뿌려줄 데이타에 @JsonView 어노테이션을 붙이면 된다. 쉽다. 이것도 마찬가지로 한가지 더 해야 될 것이 있다.
    @RequestMapping(value = "/accounts", method = RequestMethod.GET, headers = "Accept=application/json")
    @JsonView(View.Accounts.class)
    public List<Account> getAccounts() throws JsonProcessingException {
        List<Account> accounts = accountRepository.findAll();
        return accounts;
    }
위와 같이 controller 메소드에도 똑같이 넣어주자 그럼 끝. 이거 역시 매우 간단하다. 이번엔 다중으로 해보자 어떤곳은 id만 어떤곳은 id와 name 둘다.
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {

    @Id
    @GeneratedValue
    @Column(name = "account_id")
    @JsonView({
            View.Accounts.class,
            View.Account.class
    })
    private Long id;

    @NotNull
    @JsonView(View.Accounts.class)
    private String name;


    @OneToMany(mappedBy = "account")
    private List<Ordered> ordered;
}

class View {
    interface Accounts {}
    interface Account {}
}
위와 같이 배열 형태로 넣으면 된다.
    @RequestMapping(value = "/account/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    @JsonView(View.Account.class)
    public Account getAccount(@PathVariable Long id) throws IOException {
        Account account = accountRepository.findOne(id);
        return account;
    }
그런다음 account에 지정하여 보자. 그러면 id만 json 으로 나올 것이다. 이것으로 jpa의 json 순환할 경우에 대해서 알아 봤다.