Search code examples
javahibernateentity

Why we use @ForeignKey(name="FK_COUNTRY") annotation?


I have been going through some relational stuff in hibernate where I get this solution for relation between tables I tried this it works fine but when I remove @ForeignKey(name="FK_COUNTRY") nothing change then why are we using this annotation is that came under best practice?

@Entity
    @Table(name = "state")
    public class State {
        @Id
        @Column(name = "id")
        private int id;

        @Column(name = "name")
        private String name;

        @ManyToOne
        @ForeignKey(name="FK_COUNTRY")
        private Country country;
    }

Solution

  • If you read the javadoc of @ForeignKey, you'll find:

    Used to specify the handling of foreign key constraints when schema generation is in effect. If this annotation is not specified, the persistence provider's default foreign key strategy will be used.

    If you don't generate the database schema from the class definitions (e.g. CREATE TABLE SQL statement), then the annotation has no effect.