How to configure Hibernate to accept over-constrained foreign keys

I have an existing database I’d like to access using Hibernate, and I’m having trouble getting the Hibernate reverse-engineering code to accept the database’s foreign-key constraints. Typically several tables will have a diamond relationship:

Sample 'diamond' relationship

In this data model, product_dimension is only allowed to connect a product to a form_factor_measure that has the same form_factor, so product_dimension‘s foreign key constraints include form_factor_id to prevent illegal rows.

CREATE TABLE IF NOT EXISTS `mydb`.`form_factor` (
  `id` INT NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;


CREATE TABLE IF NOT EXISTS `mydb`.`product` (
  `id` INT NOT NULL,
  `form_factor_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_product_form_factor_idx` (`form_factor_id` ASC),
  CONSTRAINT `fk_product_form_factor`
    FOREIGN KEY (`form_factor_id`)
    REFERENCES `mydb`.`form_factor` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


CREATE TABLE IF NOT EXISTS `mydb`.`form_factor_measure` (
  `id` INT NOT NULL,
  `form_factor_id` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `units` ENUM('kg','cm','ml') NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_form_factor_measure_form_factor1_idx` (`form_factor_id` ASC),
  UNIQUE INDEX `name_UNIQUE` (`name` ASC),
  CONSTRAINT `fk_form_factor_measure_form_factor1`
    FOREIGN KEY (`form_factor_id`)
    REFERENCES `mydb`.`form_factor` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


CREATE TABLE IF NOT EXISTS `mydb`.`product_dimension` (
  `product_id` INT NOT NULL,
  `form_factor_measure_id` INT NOT NULL,
  `form_factor_id` INT NOT NULL,
  `dimension` DECIMAL(20,10) NOT NULL,
  PRIMARY KEY (`product_id`, `form_factor_measure_id`),
  INDEX `fk_product_dimension_product1_idx` (`product_id` ASC, `form_factor_id` ASC),
  INDEX `fk_product_dimension_form_factor_measure1_idx` (`form_factor_measure_id` ASC, `form_factor_id` ASC),
  CONSTRAINT `fk_product_dimension_product1`
    FOREIGN KEY (`product_id` , `form_factor_id`)
    REFERENCES `mydb`.`product` (`id` , `form_factor_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_product_dimension_form_factor_measure1`
    FOREIGN KEY (`form_factor_measure_id` , `form_factor_id`)
    REFERENCES `mydb`.`form_factor_measure` (`id` , `form_factor_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Hibernate doesn’t seem to like this.

Execution hbm2cfgxml of goal org.codehaus.mojo:hibernate3-maven-plugin:2.2:hbm2cfgxml failed: Foreign key (FK_hejlgxqmeb0o3enw6k89beg2a:product_dimension [form_factor_measure_id,form_factor_id])) must have same number of columns as the referenced primary key (form_factor_measure [id])

Is there a way to configure Hibernate to “just work” with foreign keys that have extra columns?


Source: java

Leave a Reply