Hi all,
I am quite new to the
EJB 3.0, which I am learning and working out examples on my own whereupon I stumbled upon this strange problem.
I was checking the exception when trying to merge an entity after removing it.
I tried it in 2 cases. One worked fine (throws an IllegalArgumentException), but the other does not.
I am using NetBeans 6.5 and GlassFish Server v2.1 for the below code.
Case 1 : (A simple one, written in the Entity Class itself. This throws an IllegalArgumentException)
@PersistenceContext EntityManager em;
public void
test (Item item) {
item = em.merge(item);
em.remove(item);
item = em.merge(item);
}
Case 2 : (This was written from a standalone client, that access the entity through an ItemFacade Session Bean)
@Stateless
public class ItemFacade implements ItemFacadeRemote {
@PersistenceContext
private EntityManager em;
....
...
..
public Item findItemByName(
String itemName) {
return (Item) em.createQuery ("select i from Item as i where item.name = \'" + itemName + "\'").getSingleResult();
}
public void merge(Item item) {
em.merge(item);
}
public void remove(Item item) {
em.remove(em.merge(item));
}
}
//Client code
ItemFacade itemFacade;
Item item = itemFacade.findItemByName("item1");
itemFacade.remove(item);
itemFacade.merge(item);
Case 2 works. No Error, and the item is not removed, but it is added to the end of the table (looks like re-added).
What makes the difference in these cases ? Is it the difference between the detached and the removed entities ? Because in Case 1, the Entity State is "removed" when the merge happens. But, in Case 2, the Entity State is "detached".
This gives me a real confusion about how remove() works now. Could anyone please throw a light on this ?
Thanks a lot :-)