在休眠中更改外键的生成名称

2022-09-01 13:57:35
@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId")
public Vehicle getVehicle() {
    return vehicle;
}

我的 UserDetails 类与 Entitity 类 Vehicle 具有一对一的映射。 创建 2 个表并分配一个通用外键,该外键将vehicle_id列(UserDetails 表)映射到主键 vehicleId(车辆表)。Hibernate

KEY FKB7C889CEAF42C7A1 (vehicle_id),
CONSTRAINT FKB7C889CEAF42C7A1 FOREIGN KEY (vehicle_id) REFERENCES vehicle (vehicleId)

我的问题是:我们如何将这个生成的外键更改为有意义的东西,例如Fk_userdetails_vehicle。


答案 1

从 JPA 2.1 开始,您可以使用 @javax.persistence.ForeignKey 注释:

@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId", foreignKey=@ForeignKey(name = "Fk_userdetails_vehicle"))
public Vehicle getVehicle() {
    return vehicle;
}

在 JPA 2.1 之前,您可以使用 Hibernate 的 @org.hibernate.annotations.ForeignKey annotation,但现在已弃用:

@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId")
@ForeignKey(name="Fk_userdetails_vehicle")
public Vehicle getVehicle() {
   return vehicle;
}

答案 2

您也可以像这样使用嵌入式:@ForeignKey@JoinColumn

@JoinColumn(name = "BAR_ID", foreignKey = @ForeignKey(name = FK_BAR_OF_FOO))

对于关系,您可以使用并嵌入如下:@ManyToManyforeignKeyinverseForeignKey@JoinTable

@JoinTable(name = "ARC_EMPLOYEE_OF_BAR"
        , joinColumns = {@JoinColumn(name = "BAR_ID")}
        , inverseJoinColumns = {@JoinColumn(name = "EMPLOYEE_ID")}
        , uniqueConstraints = {@UniqueConstraint(name = "ARC_UK_EMPLOYEE_OF_BAR", columnNames = {"EMPLOYEE_ID", "BAR_ID"})}
        , foreignKey = @ForeignKey(name = "ARC_FK_BAR_OF_EMPLOYEE")
        , inverseForeignKey = @ForeignKey(name = "ARC_FK_EMPLOYEE_OF_BAR"))

推荐