gpt4 book ai didi

java - 加入获取嵌套在 @OneToMany 中的 @ManyToOne

转载 作者:行者123 更新时间:2023-11-30 07:42:33 26 4
gpt4 key购买 nike

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

ShoppingCart.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 项; 字段不在连接中,并且对每个 ShoppingCartItem 发出单独的查询,以获取该字段 访问时

使用 EclipseLink,有没有办法在加入/批量获取 ShoppingCartItem 时也获取 Item 的加入?如何更改查询和/或代码?

最佳答案

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

关于java - 加入获取嵌套在 @OneToMany 中的 @ManyToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34456418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com