EclipseLink - 双向OneToMany关系 [英] EclipseLink - bidirectional OneToMany relation

查看:119
本文介绍了EclipseLink - 双向OneToMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个实体:

@Entity
public class Customer implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { 
        return orders; 
    }
    ...
}

@Entity
public class Order implements Serializable {
    ...
    @ManyToOne
    @JoinColumn(name="CUST_ID", nullable=false)
    public Customer getCustomer() { 
        return customer; 
    }
    ...
}

然后,我' m持久化Customer客户实体,之后,订单实体参考之前添加的客户。
当我从数据库中检索此客户并调用getOrders时,它返回空集。
这是正常行为吗?如果是,我在添加新订单实体时如何自动刷新此设置?

Then, I'm persisting Customer entity, and after that, Order entity with reference to previously added Customer. When I retrieve this customer from database, and call getOrders, it returns empty set. Is it normal behaviour? If it is, what can I do to automatically refresh this set when I add new Order entity?

推荐答案

Jpa不维护关系对于您来说,应用程序需要设置双向关系的两面以使它们与数据库保持同步。在设置order-> customer relation时将订单添加到订单列表,如果客户已分离,请将其合并以对收集的集合进行更改。

Jpa does not maintain relationships for you, the application is required to set both sides of bidirectional relationships to keep them in synch with the database. Add order to the orders list when you set the order->customer relation and if customer is detached, merge it to have the changes to the collection picked up.

否则您将需要在事务之后使用em.refresh或带有刷新查询提示的查询进行明确刷新,或者从缓存中逐出客户。无论哪种方式,它都需要通过维护关系的双方来轻松避免数据库命中。

Otherwise you will need to explicitely refresh using em.refresh or a query with a refresh query hint after the transaction, or evict the customer from the caches. Either way, it requires a database hit that is easily avoided by just maintaining both sides of relationships.

这篇关于EclipseLink - 双向OneToMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆