Murilo Carlos Cardoso
Murilo Carlos Cardoso

Reputation: 57

Spring Data JPA @JoinColumn without foreign key

I've seen some posts about it but none of them have helped me.

Why @JoinColumn(foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) doesn't work?

public class ClassA {

    @Id
    private String id;
    
    @NotNull
    private String someProperty;
    
    @OneToMany(mappedBy = "classA")
    private Set<ClassB> bs;
}


public class ClassB {
    
    @Id
    private String id;
    
    @NotNull
    private String someProperty;
    
    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private ClassA classA;
}

When the application starts it still creates the fks, although I have explicit configure to not.

create table class_a (id varchar(255) not null, some_property varchar(255), primary key (id));
   
create table class_b (id varchar(255) not null, some_property varchar(255), class_a_id varchar(255), primary key (id));

alter table if exists class_b add constraint FKjpk05raxduof60eee8p6khbch foreign key (class_a_id) references class_a

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/my-spring-data-sample
spring.datasource.username=postgres
spring.datasource.password=***

spring.jpa.hibernate.ddl-auto=create 
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect

Thanks!

Upvotes: 2

Views: 5214

Answers (1)

    @org.hibernate.annotations.ForeignKey(name = "none")
    @ManyToOne
    private ClassA classA;

    
    @OneToMany(mappedBy = "classA")
    @org.hibernate.annotations.ForeignKey(name = "none")
    private Set<ClassB> bs;

Upvotes: 4

Related Questions