1

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

购物车.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

我注意到在单个查询中按预期检索ShoppingCartItem了相同的所有 s,但该字段不在连接中,并且在访问时为每个字段发出单独的查询以获取该字段。ShoppingCart@ManyToOne private Item item;ShoppingCartItem

使用 EclipseLink,有没有办法Item在连接/批量获取ShoppingCartItems 时也获取 s 连接?如何更改查询和/或代码?

4

2 回答 2

1

如果您使用的是 EclipseLink,您可以查看@BatchFetch@JoinFetch注释。

于 2015-12-24T23:40:01.250 回答
0

虽然left join fetch带有别​​名的 s 似乎被忽略了,但我发现这个查询提示可以完成这项工作:

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不再按插入顺序返回 s。这可能是由于 EclipseLink 中的一个错误,但我认为它并没有太大的伤害,因为我实际上只需要在向用户显示购物车时订购商品,而不是,例如,当用户登录和商品时在匿名购物车中必须转移到用户购物车。

于 2015-12-25T09:53:40.483 回答