2 Replies Latest reply on Dec 29, 2005 7:37 PM by danjourno

    CascadeType.ALL

    danjourno

      I'm looking for some clarification on the CascadeType.ALL option when defining relationships between entities.

      Example: the Company entity has a property that is of Contact entity type.
      I am now creating a new Company instance and add a new Contact instance to it with

      Company company = new Company()
      company.setName("ACME PTY LTD");
      company.setAddress("123 Test St");
      Contact contact = new Contact();
      contact.setName("Daniel");
      contact.setTitle("Mr");
      ......
      company.setContact(contact);

      i now want to persist my new company instance...
      Given the fact that I have used CascadeType.ALL when defining the relationship between the contact and the company entity, I am assuming that all I need to do to persist is.
      em.persist(company);
      


      however.. this does not work and I am having to persist each object seperately as below..
      em.persist(contact);
      em.persist(company);
      


      Is my understanding of the CascadeType.ALL option wrong? Or is my code just not behaving as it should?

      Regards
      Daniel

        • 1. Re: CascadeType.ALL

          you need to ensure that both relations are populated: you set the contact into the company but not the company into the contact.
          so probably the contact is saved (you can check the db) but the id to company is empty...

          the bidirectional relations need to be filled manually on both sides (consistency)

          you have only to add a line:

          Company company = new Company()
          company.setName("ACME PTY LTD");
          company.setAddress("123 Test St");
          Contact contact = new Contact();
          contact.setName("Daniel");
          contact.setTitle("Mr");
          ...... CONTACT.SETCOMPANY(company)
          company.setContact(contact);

          • 2. Re: CascadeType.ALL
            danjourno

            ahh! That makes sense. so simple!
            Thanks for that.