users@glassfish.java.net

JPA: Delete children in OneToMany

From: <glassfish_at_javadesktop.org>
Date: Tue, 10 Feb 2009 09:45:41 PST

Hi again,

I have a new problem with a cascading delete in a unidirectional onetomany relation. I have two enteties, A and B. One instance of A can have several instances of B in a Collection. The two enteties are joined with a join table that have two columns, the PK from the table of A and B. B is not aware of the relation. I'm using Glassfish v2.1. This is the source code:<br>
<br>
@Entity<br>
@Table(name="a")<br>
public class A implements Serializable<br>
{<br>
        @Id<br>
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id", table = "a")<br>
        private int id;<br>
        
        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)<br>
        @JoinTable(name = "a_b",
                        joinColumns = {_at_JoinColumn(name = "a_fk")},<br>
                        inverseJoinColumns = {_at_JoinColumn(name = "b_fk")})<br>
        private Collection&lt;B&gt; b;<br>
        ...<br>
}<br>
<br>
@Entity<br>
@Table(name="b")<br>
public class B implements Serializable<br>
{<br>
        @Id<br>
        @GeneratedValue(strategy = GenerationType.IDENTITY)<br>
        @Column(name = "id", table = "b")<br>
        private int id;<br>
        ...<br>
}<br>
<br>

Now, how can I delete B instances from A? I have an EAO method as:<br>
public void deleteBFromA(B b, int a_id)<br>
{<br>
        A a = new A();<br>
        a.setId(a_id);<br>
        a = em.find(A.class, a.getId());<br>
<br>
        a.removeB(b); //Remove b instance from Collection in A instance<br>
        entitymanager.merge(a);<br>
}<br>
<br>
This will remove the relation between A and B in the jointable (a_b) but the B entity will not be removed from the "b" table. Is this correct behaviour? Thus, do i need to remove from "b" table manually? I would have expected that this should have been cascaded to "b" automatically.
<br>
Thanks,<br>
Mattias
[Message sent by forum member 'nightzero' (nightzero)]

http://forums.java.net/jive/thread.jspa?messageID=331071