Delete from collection [message #537417] |
Wed, 02 June 2010 08:05  |
Eclipse User |
|
|
|
Hi,
it's probably a newbie question but I can't help myself. If I remove object from collection actors, I want this was deleted from database too.
@Entity
public class Movie implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idmovie;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "movie", cascade = CascadeType.ALL)
private List<Actor> actors;
@Entity
public class Actor implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idactor;
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "idmovie")
private Movie movie;
I remove the entity this way:
movie.getActors().remove(actor);
actor.setMovie(null);
and later when I want to persist into database
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(movie);
em.getTransaction().commit();
em.close();
Any help appreciated.
Thanks
|
|
|
Re: Delete from collection [message #537533 is a reply to message #537417] |
Wed, 02 June 2010 15:09   |
Eclipse User |
|
|
|
Hi,
from persistence-2_0-final-spec:
Quote: | Bidirectional relationships between managed entities will be persisted based on references held by the
owning side of the relationship. It is the developer's responsibility to keep the in-memory references
held on the owning side and those held on the inverse side consistent with each other when they change.
In the case of unidirectional one-to-one and one-to-many relationships, it is the developer's responsibil-
ity to insure that the semantics of the relationships are adhered to.
|
This one is may test:
@Test
public void romeveBidirectional() throws Exception {
log.debug("\nGetting an Vehicle by ID.\n");
Vehicle v = em.find(Vehicle.class, "LC100");
log.debug("Object loaded: \n" + v);
assertEquals(v.getColor(), "RED");
assertEquals("Should have 2 stays", v.getStays().size(), 2);
for (Stay s : v.getStays()) {
if (s.getId().equals(100)) {
v.getStays().remove(s);
s.setVehicle(null);
}
}
//Another way:
//Stay s = em.find(Stay.class, 100);
//v.getStays().remove(s);
//s.setVehicle(null);
tx.begin();
em.merge(v);
tx.commit();
assertEquals("Should have 1 stays", v.getStays().size(), 1);
}
Gilberto
|
|
|
|
|
Powered by
FUDForum. Page generated in 1.04160 seconds