Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

java - Changing the generated name of a foreign key in Hibernate

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

My UserDetails class has a one-to-one mapping with the Entitity class Vehicle. Hibernate creates the 2 tables and assigns a generic Foreign Key, which maps the vehicle_id column (UserDetails table.) to the primary key vehicleId (Vehicle table).

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

My question is : how do we change this generated foreign key, into something meaningful, like Fk_userdetails_vehicle for example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...