0 Replies Latest reply on Sep 10, 2005 6:36 PM by Dave Chen

    Hibernate one-to-many merge ignore persistence

    Dave Chen Master

      I have a very simple one-to-many relationship: an Item has many Picture(s).

      ENTITY -- Item
      public class item {
      private Collection pictures;
      private Integer id;

      // getter/setter for id and @Id(...)

      @OneToMany(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER, mappedBy="item")
      public Collection getPictures() {
      return pictures;

      public void setPictures(Collection pictures) {
      this.pictures = pictures;

      public void addPicture(Picture p) {

      if (pictures == null)
      pictures = new ArrayList();


      ENTITY Picture --
      @ ....
      public class Picture {
      private Item item;
      private Integer id;

      // constructor
      public Picture(Item item, ....) {
      this.item = item;
      // getter/setter for id and @Id(...)

      public Item getItem() {
      return item;

      public void setItem(Item item) {
      this.item = item;

      I create an Item in persistence without any pictures. Then use a session bean to add pictures to the item.

      Session Bean --

      public class ItemManagerBean implements ItemManager {

      public void addPictureToItem(Item item, Picture p) {


      The merge() ignores those pictures that are already in persistence.
      Add picture P1: ---> persistence: P1, ( great!)
      Add picture P2 ---> persistence: P1, P1, P2 (P1 duplicated)
      Add picture P3 ---> persistence: P1, P1, P2, P1, P2, P3

      Obviously, the merge() ignored what are already in persistence. All pictures has Id. EM.merge() should be able to know P1 is already in persistence when adding P2.

      If I do not call merge(), nothing will be persisted.

      I do this from Web GUI. Transaction is thread-based.(default)

      Do I miss anything? or Is this a Hibernate bug ?


      I tried one thing: Create a picture in persistence using another session bean. Then use em.refresh(item). First time it works, and I can see the picture from item.getPictures().
      Then I create another picture the same way, and call em.refresh(item) again, but this time item.getPictures() does not have the second picture.
      Not that I have changed the Cascade type to REFRESH.

      Basically what is the way to manage the collection in one-to-many mapping?

      I am using JBoss 4.0.3RC1 on XP.

      I am very confused. Please help! Thank you.