lwinkenb wrote:
> Hello everyone, I am new to JPA and am having a little bit of trouble. I
> have two entitys: Device and Attribute. One Device can have multiple
> Attributes (annotated as OneToMany and cascade = ALL).
>
> When I add (persist) a new Device and then later add an Attribute for that
> device I cannot see the added attribute in the device's collection.
>
> For instance:
>
> Device device = new Device();
> EntityManager em = emf.createEntityManager();
> EntityTransaction tx = em.getTransaction();
> tx.begin();
> em.persist(o);
> tx.commit();
> em.close();
> // ...
> Attribute attribute = new Attribute();
> attribute.setDevice(device);
>
You have to set the relationship from both sides. That is add new
attribute to the list of attributes from device.
> EntityManager em = emf.createEntityManager();
> EntityTransaction tx = em.getTransaction();
> tx.begin();
> em.persist(o);
> tx.commit();
> em.close();
>
> device.getAttributeCollection().size() is zero at this point when I expect
> it to be one.
>
> Now if I do the following code instead...
>
> Device device;
> EntityManager em = emf.createEntityManager();
> EntityTransaction tx = em.getTransaction();
> tx.begin();
> device = (Device)em.find(Device.class, primaryKeyOfAlreadyExistingDevice);
> tx.commit();
> em.close();
> // ...
> Attribute attribute = new Attribute();
> attribute.setDevice(device);
> EntityManager em = emf.createEntityManager();
> EntityTransaction tx = em.getTransaction();
> tx.begin();
> em.persist(o);
> tx.commit();
> em.close();
>
> device.getAttributeCollection().size() is now equal to one. The only
> difference is that this time I started with a device which already existed
> in the database whereas the other time I created a new one. I am using
> TopLink as my JPA provider.
>
> When I turn on the TopLink logging I see that in the second code example
> there is a database query when I do the call
> device.getAttributeCollection().size() where in the first example there is
> no database call when I get the collection size.
>
> What am I doing wrong here?
>