persistence@glassfish.java.net

Re: Problem with OneToMany

From: Mitesh Meswani <Mitesh.Meswani_at_Sun.COM>
Date: Tue, 22 Apr 2008 16:53:00 -0700

JPA does not have manged relationship. To write a portable app, you will
need to update both of a relationship manually. Something like as follows..

Colection<Transaction> transactions = .....
for (Transaction transaction : transactions )
{
        transaction.setCard(card);
        em.update(transaction); //BTW, what is em.update???
}

card.setTransactions(transactions);

MrFishKill wrote:
> Hi,
>
> I have a problem when 'persist' a new entity and 'update' his childs
> (OneToMany).
> It seems like first entity don't refresh!!!
>
> These are my 2 entities with a OneToMany and ManyToOne relation:
>
> ----------------------------------------------------
> Entity
> @Table(name = "cards")
> public class Card implements Serializable
> {
> @Id
> @GeneratedValue(strategy=GenerationType.SEQUENCE)
> @Column(name="id_card")
> private int idCard;
>
> @OneToMany(fetch = FetchType.LAZY, mappedBy = "card", cascade =
> CascadeType.ALL)
> @JoinColumn(name = "id_card")
> List<Transaction> transactions;
> ...
> }
>
> @Entity
> @Table(name = "transactions")
> public class Transaction
> {
> @Id
> @GeneratedValue(strategy=GenerationType.SEQUENCE)
> @Column(name = "id_transaction")
> private int idTransaction;
>
> @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
> @JoinColumn(name = "id_card")
> private Card card;
> ....
> }
>
> ----------------------------------------------------
> And this is my code:
> ----------------------------------------------------
> ....
> em.getTransaction().begin();
> Card card = new Card();
> ....
> card.setName('fff');
> ....
> ....
>
> em.persist(card);
> ....
> ....
> Colection<Transaction> transactions = .....
> for (Transaction transaction : transactions )
> {
> transaction.setCard(card);
> em.update(transaction);
> }
> int num_transactions = card.getTransactions().size();
> em.getTransaction().commit();
>
> System.out.println("Num Transactions:"+num_transactions); <---------------
> SHOW ME ZERO RESULTS!!!!
> ----------------------------------------------------
>
> Last line show me 0 results!!!! Why????????
>
> Thanks in advance,
>
>