Hi David,
What happens if you change your code to do the following:
Item parent = new Item();
Item child = new Item();
Item child2 = new Item();
children.add(child);
children.add(child2);
child1Items.add(parent);
child2Items.add(parent);
parent.setRelatedItems(children);
child1.setItems(child1Items);
child2.setItems(child2Items);
em.getTransaction().begin();
em.persist(item);
em.getTransaction().commit();
The JPA specification dictates that you have to maintain both sides of bidirectional relationahips yourself.
-Tom
David Harrigan wrote:
>Hi,
>
>Java 6 (update 1).
>Glassfish v2 build = tracking cvs.
>
>Background:
>
>One class, doing a self-referential many-to-many (code has been cropped):
>
>@Entity
>public Class Item {
>
> @Id
> private int itemId;
>
> @ManyToMany(cascade = {PERSIST, MERGE, REFRESH})
> @JoinTable("ITEMRELATEDITEM")
> private Set<Item> relatedItems;
>
> @ManyToMany(mappedBy = "relatedItem")
> private Set<Item> items;
>
>}
>
>If I then do:
>
>Item parent = new Item();
>Item child = new Item();
>Item child2 = new Item();
>
>children.add(child);
>children.add(child2);
>
>parent.setRelatedItems(children);
>
>em.getTransaction().begin();
>em.persist(item);
>em.getTransaction().commit();
>
>All 3 entities get inserted into the database (assume ids, parent = 1,
>child = 2 and child = 3)
>
>In the ITEMRELATEDITEM table, these rows exist:
>
>RELATEDITEMS_ITEMID ITEMS_ITEMID
>2 1
>3 1
>
>Okay, subsequentially, if I now do the following:
>
>parent = null;
>child = null;
>child2 = null;
>
>parent = em.find(Item.class, 1);
>
>I get back the Parent Item object, but, if I then do:
>
>parent.getRelatedItems()
>
>this returns an empty set - always.
>
>Even if I put FetchType.EAGER on the two annotated fields.
>
>If I try this within a container (GF, current cvs), it works, in that
>getRelatedItems returns back a set with 2 items in it.
>
>Is there a problem with this in JavaSE?
>
>
>-=david=-
>
>
>
>