Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override joined-inheritance foreign key name with JPA/Hibernate

I have a class CD with inherit from class Media:

CD:

@Entity
public class CD extends Media {
   ...
}

Media:

@Entity(name = "media")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Media extends PersistenceId<Long> {
   ...
}

JPA generates automatically a foreign key name and I would like to override this with the name I want:

03-10 18:16:58.174 [main] DEBUG org.hibernate.SQL - alter table cd add constraint FK_ehd468g2cptgh6bq6sxe75xlf foreign key (id) references media (id)

How to do that ? I tried:

@Entity
@AssociationOverride(
   name = "id",
   foreignKey = @ForeignKey(name = "fk_cd_media")
)
public class CD extends Media {
   ...
}

and

@Entity
@PrimaryKeyJoinColumn(foreignKey=@ForeignKey(name = "fk_cd_media"))
public class CD extends Media {
   ...
}

but it doesn't work.

Here is the create table sql generated:

CREATE TABLE `cd` (
  `artist` varchar(255) DEFAULT NULL,
  `year` int(11) NOT NULL,
  `id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `FK_ehd468g2cptgh6bq6sxe75xlf` FOREIGN KEY (`id`) REFERENCES `media` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

I would like:

CONSTRAINT `fk_cd_media` FOREIGN KEY (`id`) REFERENCES `media` (`id`)
like image 202
Steph Avatar asked Oct 03 '15 16:10

Steph


1 Answers

Your second attempt is the way to go:

@Entity
@PrimaryKeyJoinColumn(foreignKey=@ForeignKey(name = "fk_cd_media"))
public class CD extends Media {
   ...
}

The problem is you're facing a Hibernate bug: https://hibernate.atlassian.net/browse/HHH-10352

Edit: The problem is solved:

Fix Version/s: 5.0.10, 5.2.1, 5.1.1

like image 153
Jaindson Santana Avatar answered Nov 03 '22 03:11

Jaindson Santana