user1315305
user1315305

Reputation: 1389

EclipseLink - bidirectional OneToMany relation

Let's say I have two entities:

@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; 
    }
    ...
}

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?

Upvotes: 2

Views: 1575

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

If you retrieve the customer from the same transaction, then yes, it's expected behavior. The reason is that the EntityManager returns the order it has in its first-level cache, and that you created yourself, without adding any order to its set of orders. It's your responsibility to maintain the coherence of the object graph by maintaining the two sides of the association:

order.setCustomer(customer);
customer.addOrder(order);

Upvotes: 2

Chris
Chris

Reputation: 21145

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.

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.

Upvotes: 7

Related Questions