@OneToMany MappedBy behaviour - list not initialized [message #654850] |
Thu, 17 February 2011 07:39  |
Eclipse User |
|
|
|
I am having difficulty following the basic one-to-many mappedBy behaviour. Basically an entity retrieval where mappedBy is used does not return an initilized list in the owning entity. Whilst if no mappedBy is used the collection is initilized.
core unit test:
// setup - populate & persist an order with 1 item.
// test..
Order order= (Order) entityManager.find(Order.class, validOrderID);
assertEquals(1, order.getItems().size());
Order contains a collection of Items, I would expect retrieving the Order in both cases would bring back an Order instance with items containing a list with 0 or more elements, but never null. practically if mappedBy is used then items is null, if mappedBy is not used the list is as expected - What am I misunderstanding?
@Entity
public class Item {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@ManyToOne
private Order order;
public Order getOrder() {
return order;
}
public Long getId() {
return id;
}
}
@Entity
@Table(name="T_ORDER")
public class Order {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "order", cascade=CascadeType.ALL)
//@OneToMany( cascade=CascadeType.ALL)
@JoinColumn(name="ORDER_ID")
private Collection<Item> items = new LinkedHashSet<Item>();
public Collection<Item> getItems() {
return items;
}
public void setItems(Collection<Item> items) {
this.items = items;
}
public Long getId() {
return id;
}
}
(EclipseLink, within STS, + embedded db & DB2)
|
|
|
|
|
Re: @OneToMany MappedBy behaviour - list not initialized [message #654971 is a reply to message #654932] |
Thu, 17 February 2011 14:59  |
Eclipse User |
|
|
|
Hello,
The database relationship is controlled by the 'owning' side when the entities have a bidirectional relationship. So you can update only one side, but the java objects will not reflect the change on the other side until they are refreshed. Entities are just plain java objects cached within the EntityManager. So its best practice to update both sides so that your cache is in synch with what is in the database. Same thing goes for deleting an object - the application should null out any references to it or there will be inconsistencies in the cache.
Best Regards,
Chris
|
|
|
Powered by
FUDForum. Page generated in 0.03316 seconds