使用JPA / Hibernate

时间:2015-10-03 16:44:38

标签: mysql hibernate jpa foreign-keys

我有一张继承自Media类的CD:

CD:

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

媒体:

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

JPA自动生成一个外键名称,我想用我想要的名称覆盖它:

  

03-10 18:16:58.174 [main] DEBUG org.hibernate.SQL - alter table cd add   约束FK_ehd468g2cptgh6bq6sxe75xlf外键(id)引用   媒体(id)

怎么做?我试过了:

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

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

但它没有用。

这是生成的create table sql:

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;

我想:

CONSTRAINT `fk_cd_media` FOREIGN KEY (`id`) REFERENCES `media` (`id`)

1 个答案:

答案 0 :(得分:2)

你的第二次尝试是要走的路:

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

问题是您遇到了Hibernate错误:https://hibernate.atlassian.net/browse/HHH-10352

编辑:问题解决了:

  

修复版本:5.0.10,5.2.1,5.1.1