问题
This is for a legacy database. The two database tables in this relationship don't have a foreign key constraint even though the child table column holds the PK of the parent table.
Does JPA support a @OneToMany mapping (either bidirectional or unidirectional) if the child table does not have a foreign key constraint on the appropriate column?
回答1:
Short answer: yes.
Long one: does JPA actually care about foreign keys if the database already exists? If we leave the task of creating the database schema to JPA provider, it will create foreign keys, which is good. But if the JPA works on existing database, it only cares about the existence of foreign key and primary key columns to produce proper joins. Foreign keys aren't necessary.
In fact while I worked with Hibernate we've had a legacy database using short
type for foreign key column to point to int
primary key on the other table. There couldn't be any foreign key, but as long as we didn't use validate
hbm2ddl
option, Hibernate as JPA provider was working just fine, ignoring type mismatch, not to mention the lack of foreign keys.
来源:https://stackoverflow.com/questions/5083611/does-jpa-support-a-onetomany-mapping-between-entities-without-a-foreign-key-con