简体   繁体   English

JPA:外键注释

[英]JPA: foreign key annotation

I've got two database entities: Forum and Topic . 我有两个数据库实体: ForumTopic

Topic has protected long forumId data member, which indicates of course the Topic 's forum. Topic已经protected long forumId数据成员,这当然表明了Topic论坛。

My question is what annotation to use for this data member? 我的问题是这个数据成员使用的注释是什么?

As Forum has many topics, and a topic belongs to one and only Forum, you probably want to go with a Forum type attribute annotated with @ManyToOne : 由于论坛有很多主题,并且某个主题属于唯一的论坛,因此您可能希望使用@ManyToOne注释的论坛类型属性:

@ManyToOne
@JoinColumn(name = "forumId")
private Forum forum;

See more: 看更多:

ManyToOne and JPA mapping ManyToOneJPA映射

As others have answered - 正如其他人已经回答 -
You should use the ManyToOne , and JoinColumn annotations. 您应该使用ManyToOneJoinColumn注释。
Bare in mind , that since JPA is about ORM - Object relational mapping, 请记住,因为JPA是关于ORM - 对象关系映射,
You should reference another object as you would have done "naturally" in Java - ie via an object and not via its identifier (which is forumId) in your case), 您应该像在Java中“自然地”那样引用另一个对象 - 即通过对象而不是通过其标识符(在您的情况下是forumId)),
This was one of the design consideration between the relations at JPA and Hibernate (previously to JPA). 这是JPA和Hibernate(之前对JPA)关系之间的设计考虑之一。

@ManyToOne正如注释所暗示的那样 - 每个论坛都有很多主题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM