我有三个数据库表:Customer,Product和PurchaseOrder(用于映射)。我在java rest应用程序中使用openjpa进行存活。 对于所有表,我都有相应的实体: 客户
@Entity
@Table(name = "customer")
@XmlRootElement
@NamedQueries({...})
public class Customer implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customerId")
private Collection<PurchaseOrder> purchaseOrderCollection;
产品
@Entity
@Table(name = "product")
@XmlRootElement
@NamedQueries({...})
public class Product implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "productId")
private Collection<PurchaseOrder> purchaseOrderCollection;
的PurchaseOrder
@Entity
@Table(name = "purchase_order")
@XmlRootElement
@NamedQueries({..})
public class PurchaseOrder implements Serializable {
...
@Id
@Basic(optional = false)
@Column(name = "order_num")
private Integer orderNum;
@JoinColumn(name = "customer_id", referencedColumnName = "customer_id")
@ManyToOne(optional = false)
private Customer customer;
@JoinColumn(name = "product_id", referencedColumnName = "product_id")
@ManyToOne(optional = false)
private Product product;
获得订购具有特定ID的产品的所有客户的最佳方式是什么? 我可以创建 namedQuery,我可以使用连接等建立标准但是我认为如何使用映射实体可能有更好的方法(这个实体还有什么意义呢?)。有点像将productId设置为purchaseOrder实体,然后通过客户实体中的purchaseOrderCollection获取所有客户?但我无法弄明白。除了自定义/命名查询或标准之外,还有其他方法吗? 感谢。
答案 0 :(得分:0)
好吧我明白了,它可以这样
long productId = //get the id
Product product = entityManager.find(Product.class, productId);
Collection<PurchaseOrder> purchaseOrderCollection = product.getPurchaseOrderCollection();
if (purchaseOrderCollection != null) {
List<Integer> customers = new ArrayList<>(product.getPurchaseOrderCollection().size());
for (PurchaseOrder purchaseOrder : product.getPurchaseOrderCollection()) {
customers.add(purchaseOrder.getCustomerId());
}
return customers;
} else {
return Collections.EMPTY_LIST; // or null;
}
随时提供更好的溶液:)