加入抓取嵌套在@OneToMany中的@ManyToOne



我创建了以下实体来管理持久购物车:

购物车.java:

@Entity
public class ShoppingCart {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @PrivateOwned
    @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL)
    @OrderBy("creationTimestamp")
    private List<ShoppingCartItem> items;
    public ShoppingCart() {}
    // Getters and setters...
}

ShoppingCartItem.java:

@Entity
@IdClass(ShoppingCartItemId.class)
public class ShoppingCartItem {
    @Id
    @ManyToOne
    private Item item;
    @Id
    @ManyToOne
    private ShoppingCart cart;
    private int quantity;
    @Column(precision = 17, scale = 2)
    private BigDecimal price;
    @Temporal(TemporalType.TIMESTAMP)
    private Date creationTimestamp;
    protected ShoppingCartItem() {}
    @PrePersist
    protected void prePersist() {
        creationTimestamp = new Date();
    }
    public ShoppingCartItem(ShoppingCart cart, Item item, int quantity) {
        this.cart = cart;
        this.item = item;
        this.quantity = quantity;
        this.price = item.getPrice();
    }
    // Getters and setters...
}

项目.java:

@Entity
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne
    private Brand brand;
    private String model;
    private String variant;
    private String description;
    @Column(precision = 17, scale = 2)
    private BigDecimal price;
    private int availability;
    protected Item() {}
    // Constructors, getters and setters...
}

当我发出以下JPQL查询时:

SELECT c FROM ShoppingCart c JOIN FETCH c.items WHERE c.id = :id

我注意到,同一ShoppingCart中的所有ShoppingCartItem都是在单个查询中按预期检索的,但@ManyToOne private Item item;字段不在联接中,并且当访问时,会为每个ShoppingCartItem发出一个单独的查询来获取该字段

使用EclipseLink,是否有一种方法可以在连接/批量获取ShoppingCartItem时也获取Item的连接?如何更改查询和/或代码?

如果您正在使用EclipseLink,您可以查看@BatchFetch和@JoinFetch注释。

虽然带有别名的left join fetch似乎被忽略了,但我发现了以下查询提示:

Query query = entityManager.createQuery("SELECT c FROM ShoppingCart c WHERE c.id = :id");
query.setHint("eclipselink.left-join-fetch", "c.items.item.brand");

这可能比注释方法更好,因为它可以为单个查询指定。


更新

使用此提示会破坏@OrderBy("creationTimestamp"),因此ShoppingCartItem不再按插入顺序返回。这可能是由于EclipseLink中的一个错误造成的,但我认为这并没有造成太大的伤害,因为我实际上只需要在向用户显示购物车时订购物品,而不是在用户登录时,匿名购物车中的物品必须转移到用户购物车。

最新更新