springjpa中关系的java动态获取

p5cysglq  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(180)

我希望能够动态加载实体的关系,这取决于调用了哪个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();
}

这两种类型都不是 LAZY 以及 EAGER 或json注解(如 @JsonIgnore , @JsonIdentityInfo , @JsonManagedReference 以及 @JsonBackReference )就我的理解和努力而言,似乎使这成为可能。
如果这是不可能的,也许有人可以解释如何解决这个问题,然后。一方面,我有时需要前端中的这些关系来显示一些值,另一方面,当我总是加载它们时,我会遇到巨大的性能问题或无穷递归。

2q5ifsrm

2q5ifsrm1#

我不认为jpa直接支持您的用例。
一种方法是创建同一个实体两次,一次使用eager,另一次使用lazy。在方法上切换。
另一种选择是使用dto(数据传输对象)作为响应,而不是实体类本身。不过,您必须编写Map器逻辑才能将实体转换为dto。

相关问题