Java Spring JPA中关系的动态抓取
我希望能够动态加载实体的关系,这取决于调用了哪个RestService 实体类:Java Spring JPA中关系的动态抓取,java,spring,jpa,orm,relation,Java,Spring,Jpa,Orm,Relation,我希望能够动态加载实体的关系,这取决于调用了哪个RestService 实体类: @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ManyToOne private Buyer buyer; // some more attributes } @Entity public class Buy
@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();
}
@GetMapping
公共Iterable getAll(){
//这里我希望JPA不要加载订单的买家
return orderRepository.findAll();
}
@GetMapping(“/{id}”)
公共命令获取(@PathVariable(“id”)字符串id){
//在这里,我希望JPA加载订单的买家
return orderRepository.findById(Long.parseLong(id)).orelsetrow();
}
就我的理解和尝试而言,两种fetchTypeLAZY
和EAGER
或json注释(如@JsonIgnore
,@JsonIdentityInfo
,@JsonManagedReference
和@JsonBackReference
)似乎都无法实现这一点
如果这是不可能的,也许有人可以解释一下如何解决这个问题。一方面,我有时需要前端中的这些关系来显示一些值,另一方面,当我总是加载它们时,我会遇到巨大的性能问题或无限递归。我认为JPA不直接支持您的用例 一种方法是创建同一实体两次,一次使用eager,另一次使用lazy。在方法中切换它们
另一种选择是使用DTO(数据传输对象)作为响应,而不是实体类本身。您必须编写映射器逻辑才能将实体转换为DTO。您可能正在查找
@EntityGraph
。谢谢!!这正是我要搜索的:)有一种方法@EntityGraph正是这样做的。