Changing the generated name of a foreign key in Hibernate

后端 未结 4 1107
独厮守ぢ
独厮守ぢ 2020-12-13 09:56
@OneToOne()
@JoinColumn(name=\"vehicle_id\", referencedColumnName=\"vehicleId\")
public Vehicle getVehicle() {
    return vehicle;
}

My UserDetails

相关标签:
4条回答
  • 2020-12-13 10:12

    May be you should try this, adding @ForeignKey annotation :

    @ManyToOne
    @ForeignKey(name="FK_some_model")
    @JoinColumn(name="some_model_id")
    private SomeModel someModel
    
    0 讨论(0)
  • 2020-12-13 10:13

    You can do it also by implementing ImplicitNamingStrategy.determineForeignKeyName and using

    configuration.setImplicitNamingStrategy(
        new MyImplicitNamingStrategy())
    

    which is nice as you don't have to do it manually again and again. However, it may be hard to put the relevant information there. I tried to concat everything I got (using three underscore to separate the parts) and ended up with

    FK_ACCESS_TEMPLATE____TEMPLATE____TEMPLATE_ID____TEMPLATE_ID__INDEX_B
    

    which isn't really better than

    FKG2JM5OO91HT64EWUACF7TJCFN_INDEX_B
    

    I guess, using just the referenced table and column names together with a number for uniqueness would be just fine.


    Note also that this seems to be legacy Hibernate stuff, unsupported by JPA.

    OTOH it works with Hibernate 5.0.1 (just one week old).

    0 讨论(0)
  • 2020-12-13 10:15

    Since JPA 2.1, you can use the @javax.persistence.ForeignKey annotation:

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

    Prior to JPA 2.1, you could use Hibernate’s @org.hibernate.annotations.ForeignKey annotation, but this is now deprecated:

    @OneToOne()
    @JoinColumn(name="vehicle_id", referencedColumnName="vehicleId")
    @ForeignKey(name="Fk_userdetails_vehicle")
    public Vehicle getVehicle() {
       return vehicle;
    }
    
    0 讨论(0)
  • 2020-12-13 10:33

    Also you can use @ForeignKey embedded in @JoinColumn like this:

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

    for @ManyToMany relations you can use foreignKey and inverseForeignKey embedded in @JoinTable like this:

    @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"))
    
    0 讨论(0)
提交回复
热议问题