4 Replies Latest reply on Apr 3, 2006 6:57 AM by oliverchua

    Recursive Bidirectional entity

    oliverchua

       

      @Entity
      public class Unit implements Serializable{
       @Id @GeneratedValue
       private Long unitCode;
       private String unitName;
       @ManyToOne @JoinColumn(name="superUnitCode")
       private Unit superUnit;
       @OneToMany(mappedBy="subUnits")
       private Set<Unit> subUnits;
       @Transient
       private String superUnitCode;


      Hi I have this entity class.
      The OneToMany is bidirectional and recursive.
      IT adds
      CONSTRAINT `FK284DA4E626B09B` FOREIGN KEY (`unitCode`) REFERENCES `unit` (`unitCode`)
      that prevents any inserts to the table.

      What should I do to remove the constraint?
      Thanks in advance.

        • 1. Re: Recursive Bidirectional entity
          epbernard

          constraints does not prevent bidirectional and recursive associations

          • 2. Re: Recursive Bidirectional entity
            oliverchua

            Hi Emmanuel, this is the script of the table that was created by hibernate...

            CREATE TABLE `intranetejb`.`unit` (
             `unitCode` bigint(20) NOT NULL auto_increment,
             `unitName` varchar(255) default NULL,
             `superUnitCode` bigint(20) default NULL,
             PRIMARY KEY (`unitCode`),
             KEY `FK284DA4E626B09B` (`unitCode`),
             KEY `FK284DA41AB47516` (`superUnitCode`),
             CONSTRAINT `FK284DA41AB47516` FOREIGN KEY (`superUnitCode`) REFERENCES `unit` (`unitCode`),
             CONSTRAINT `FK284DA4E626B09B` FOREIGN KEY (`unitCode`) REFERENCES `unit` (`unitCode`)
            ) ENGINE=InnoDB DEFAULT CHARSET=latin1;


            When I am trying to insert a record in the database (not in EJB)
            INSERT INTO `unit` (`unitCode`, `unitName`, `superUnitCode`) VALUES
            (1,'My unit',NULL)

            I get this error...
            Cannot add or update a child row: a foreign key constraint fails (`intranetejb/unit`, CONSTRAINT `FK284DA4E626B09B` FOREIGN KEY (`unitCode`) REFERENCES `unit` (`unitCode`))


            When I delete the constraint, I'm able to insert the record.

            • 3. Re: Recursive Bidirectional entity
              epbernard

              Oh I found you problem, mappedBy="subUnits" should be mappedBy="superUnit", you should reference the many side not something else

              • 4. Re: Recursive Bidirectional entity
                oliverchua

                Emmanuel,

                Thanks! that solved the problem