JPA 是否支持数据库中没有外键约束的实体之间的 @OneToMany 映射?
这是针对遗留数据库的。即使子表列保存父表的 PK,此关系中的两个数据库表也没有外键约束。
如果子表在适当的列上没有外键约束,JPA 是否支持 @OneToMany 映射(双向或单向)?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短回答:是。
长话短说:如果数据库已经存在,JPA 真的关心外键吗?如果我们将创建数据库模式的任务留给 JPA 提供者,它将创建外键,这很好。但是,如果 JPA 在现有数据库上工作,它只关心外键和主键列是否存在以产生正确的连接。外键不是必需的。
事实上,当我使用 Hibernate 时,我们有一个旧数据库,使用
short
类型作为外键列来指向另一个表上的int
主键。不可能有任何外键,但只要我们不使用validate
hbm2ddl
选项,Hibernate 作为 JPA 提供程序就可以正常工作,忽略类型不匹配,而不是值得一提的是缺少外键。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 toint
primary key on the other table. There couldn't be any foreign key, but as long as we didn't usevalidate
hbm2ddl
option, Hibernate as JPA provider was working just fine, ignoring type mismatch, not to mention the lack of foreign keys.