Search code examples
javahibernatejpajdbc

JPA @OneToMany with out Db constaraint


Asking if this is Possible Or Impossible

Can we Create Java JPA Mapping "@OneToMany" without having DB constraint such as PrimaryKey , ForeignKey creation on the Db table ?

Reason

When creating a normal SQL Query we JOIN 2 Tables by the Column constrains ( if equals ) with out creating PK or FK constrains .


Solution

  • Yes. You can refer to a column that is not a PK. And you can ask Hibernate to not create a FK:

    @ManyToOne
    @JoinColumn(referencedColumnName = "not_an_id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private Owner owner;