Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA association without foreign key

Tags:

hibernate

jpa

Is it possible to set up a ManyToOne association without JPA creating a foreign key in the database?

The tables are owned by another system and are populated asynchronously. Thus we can't have a FK in the database. There's still, almost always, eventually a relation.

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
        @JoinColumn(name="`Order Type`", referencedColumnName = "`Order Type`", insertable = false, updatable = false),
        @JoinColumn(name="`Order No`", referencedColumnName = "`No`", insertable = false, updatable = false)
}, foreignKey = @javax.persistence.ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
private OrderHeader orderHeader;

The problem is that JPA SchemaUpdate tries to add a FK even though ConstraintMode.NO_CONSTRAINT

[error] o.h.t.h.SchemaUpdate - Cannot add foreign key constraint

and we could ignore that if it didn't make the rest of the statements fail

[error] o.h.t.h.SchemaUpdate - No operations allowed after statement closed.

We're on hibernate-entitymanager 4.3.7.Final and JPA 2.1.

like image 707
Jonas Elfström Avatar asked Nov 20 '14 13:11

Jonas Elfström


1 Answers

The fact that ConstraintMode.NO_CONSTRAINT is ignored looks like a bug in Hibernate 4 due to be fixed in 5.

https://hibernate.atlassian.net/browse/HHH-8805

The comments on that and indeed this post here:

Multiple relationships with single mapping table without generating foreign keys by Hibernate

suggest adding the deprecated (hibernate rather than JPA) annotation

@ForeignKey( name = "none" )

to the relationship should work.

like image 102
Alan Hay Avatar answered Dec 27 '22 10:12

Alan Hay