我希望能够动态加载实体的关系,具体取决于调用的 RestService。
实体类:
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
private Buyer buyer;
// some more attributes
}
@Entity
public class Buyer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
// some more attributes
}
RestController 类:
@GetMapping
public Iterable<Order> getAll() {
// here I want JPA to NOT load the buyers for the order
return orderRepository.findAll();
}
@GetMapping("/{id}")
public Order get(@PathVariable("id") String id) {
// here I want JPA to load the buyers for the order
return orderRepository.findById(Long.parseLong(id)).orElseThrow();
}
两种 fetchtypes LAZY
和 EAGER
或 json 注释都没有(例如 @JsonIgnore
、@JsonIdentityInfo
)据我理解和尝试,@JsonManagedReference
和 @JsonBackReference
)似乎使这成为可能。
如果这是不可能的,也许有人可以解释如何解决这个问题。一方面,我有时需要在前端中显示这些关系来显示一些值,另一方面,当我总是加载它们时,我会遇到巨大的性能问题或无限递归。
最佳答案
我认为 JPA 不直接支持您的用例。
一种选择是创建同一实体两次 - 一次使用 eager,另一次使用惰性。在方法中切换它们。
另一种选择是使用 DTO(数据传输对象)作为响应,而不是实体类本身。不过,您必须编写映射器逻辑来将实体转换为 DTO。
关于java - Spring JPA 中关系的动态获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886796/