在用JPA时碰到一个坑爹问题在实体entity中配置Set<>后查出来的数据每次结果不一样,代码如下:
List<OrderDetails> orderDetailsList=new ArrayList<>(); @OneToMany(fetch = FetchType.EAGER) @JoinColumn(name = "orderId", referencedColumnName = "orderId", insertable = false, updatable = false) public List<OrderDetails> getOrderDetailsList() { return orderDetailsList; }
然后换成List,但是查出来的数据很多重复的数据,代码如下:
List<OrderDetails> orderDetailsList=new ArrayList<>(); @OneToMany(fetch = FetchType.EAGER) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "orderId", referencedColumnName = "orderId", insertable = false, updatable = false) public List<OrderDetails> getOrderDetailsList() { return orderDetailsList; }
最后解决办法, 再添加一个注解@Fetch(FetchMode.SUBSELECT)
代码如下:
List<OrderDetails> orderDetailsList=new ArrayList<>(); @OneToMany(fetch = FetchType.EAGER) @Fetch(FetchMode.SUBSELECT) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "orderId", referencedColumnName = "orderId", insertable = false, updatable = false) public List<OrderDetails> getOrderDetailsList() { return orderDetailsList; }
@Fetch(FetchMode.SUBSELECT)这个注解的意思 是先查当前Entity 生成一个SQL,然后这个OneToMany再单独生成一个sql再去查询。可以看生成的SQL日志可以看出来。。
参考:https://www.cnblogs.com/fashflying/p/5147473.html