Java – How to specify foreign key with the join column

hibernatejavajpaspringspring-boot

My code is as below. I am using the spring boot with jpa and postgresql database
I need user friendly name as foreign key.


    @Entity
    @Table(name="course_table")
    public class Course extends BaseAuditingEntity {

    @ManyToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
    @JoinTable(name = "course_program_table", joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "course_id", foreignKey = @ForeignKey(name = "fk_program_id")), inverseJoinColumns = @JoinColumn(name = "program_id", referencedColumnName = "program_id", foreignKey = @ForeignKey(name = "fk_course_id")))
    private List programs;
    }

I have given the name of foreign key using the @ForeignKey annotation but when I see db it is showing the randomly created foreignkey name.

CREATE TABLE course_program_table
(
    course_id integer NOT NULL,
    program_id integer NOT NULL,
    CONSTRAINT fk_28c95hl4nqclyvyxuduei5nbf FOREIGN KEY (program_id)
        REFERENCES public.program_table (program_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fk_5sainywquv8yyu24pjk3jptn7 FOREIGN KEY (course_id)
        REFERENCES public.course_table (course_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

I need foreign key as mentioned in the annotation like fk_program_id and fk_course_id.

Thanks in advance.

Best Answer

With a join table this is how you should specify it

@ManyToMany
@JoinTable(name = "course_program_table", 
    joinColumns = @JoinColumn(name = "course_id", ...)
    foreignKey = @ForeignKey(name = "fk_program_id"), 
    inverseJoinColumns = @JoinColumn(name = "program_id", ...)
    inverseForeignKey = @ForeignKey(name = "fk_course_id"))
private List programs;

This is how I do it with the JPA provider I use (not Hibernate), and that is why the @JoinTable has the "foreignKey"/"inverseForeignKey" attributes (the FKs are on/owned by the join table).

If that doesn't work then you need to be looking at raising a bug on your chosen JPA provider.

Related Topic