gpt4 book ai didi

Java Spring 数据 JPA 和 REST API : exclude fields of nested JSON object

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:24 24 4
gpt4 key购买 nike

目前,我使用 Spring Data JPA 2.2.1 和 Spring Boot Web 2.2.1 来实现 REST API 服务。

/categories 的 getter 调用返回以下 JSON,这实际上是所需的结果:

[
{
"category1": "A",
"category2": "B",
"subcategories": []
},
{
"category1": "A",
"category2": "B",
"subcategories": [{
"field1": "A",
"field2": "B",
"field3": "C",
"field4": "D"
}]
},
.........
.........
]

实体:

@Entity
@Table(name = "category")
@Getter @Setter
public class Category {

@JsonIgnore
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String category1;
private String category2;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Subcategory> subcategories;
}
@Entity
@Table(name = "subcategory")
@Getter @Setter
public class Subcategory {

@JsonIgnore
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@JsonIgnore
private int parent;
private String field1;
private String field2;
private String field3;
private String field4;
}

Controller :

@RestController
public class MyController {

private final DataService dataService;

@Autowired
public MyController(DataService dataService) {
this.dataService = dataService;
}

@GetMapping("/categories")
public List<Category> getAllCategories() {
return dataService.getAllCategories();
}

存储库

public interface MyRepository extends JpaRepository<Category, Long> {
List<MyRepository> findAll();
}

数据服务

@Component
public class DataService {
private MyRepository myRepository;

@Autowired
public DataService(MyRepository myRepository) {
this.myRepository = myRepository;
}

public List<Category> getAllCategories() { return myRepository.findAll(); }

我现在想要添加对我的 API /limitedCategories 的新调用,该调用不会返回所有字段。例如,父实体的“category2”和嵌套实体的“field4”应被排除。

问题:

  • 我无法在 JPA 存储库中手动选择所需的字段,也不知道如何处理嵌套对象。
  • 仅使用 findAll 并使用 @JsonIgnore 排除这些字段的简单想法是不可能的,因为我的第一个请求仍然需要这些字段。
  • 当在我的存储库中使用 @Query 注释仅获取所需字段时,我找不到获取 JSON 嵌套字段的方法。

提前致谢。

我将 Spring Data JPA 2.2.1 与 Spring Boot Web 2.2.1 结合使用。

最佳答案

如果您使用 Jackson API,我建议您使用 @JsonView 功能。

例如

class Person {
// it will be add always
Integer id;

// it will be add only for PutFirstName case
@JsonView(Views.PutFirstName.class)
String firstName;

// it will be add only for PutLastName case
@JsonView(Views.PutLastName.class)
String lastName;
}

class Views {
static class PutFirstName{}
static class PutLastNastName{}
}

// Controller
@JsonView(Views.PutFirstName.class)
@GetMapping
Person getFirstName(){
// result : {id,firstName}
}

@JsonView(Views.PutLastName.class)
@GetMapping
Person getLastName(){
// result : {id, lastName}
}

关于Java Spring 数据 JPA 和 REST API : exclude fields of nested JSON object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com