views:

202

answers:

1

Java EJB's EntityManager does not update data from a Consumer.

A Consumer logs into a shop, buys some stuff and wants to look at his shopping-history. Everything is displayed but his last purchase. If he logs out and in, it shows.

I have used JPA to persist buys/purchases (that are mapped to the Consumer)to DB. It seems like purchases from this session can't be detected.

Code:

public Buys buyItem(Consumer c, int amount) {
    Buys b = new Buys();
    b.setConsumerId(c);
    b.setContent("DVD");
    b.setPrice(amount);
    em.persist(b);
    em.flush();
    return b;
}

public Collection getAllBuysFromUser(Consumer consumer) {
   Collection<Buys> collection = consumer.getBuysCollection();
   return collection;
}

Help!? Flush does not do the trick...

+1  A: 

You seem to have a bi-directional one-to-many association between Customer and Buys but I don't see where you add the Buys instance to the buysCollection on the Customer side. I'd expect to see something like this:

public Buys buyItem(Consumer c, int amount) {
    Buys b = new Buys();
    b.setConsumerId(c);
    b.setContent("DVD");
    b.setPrice(amount);
    c.getBuysCollection().add(b);
    em.persist(b);
    em.flush();
    return b;
}

And make sure you implement equals (and hashCode) properly.

I suggest to check 1.2.6. Working bi-directional links (and to add defensive link management methods as suggested).

Pascal Thivent

related questions