39

I've got two database entities: Forum and Topic.

Topic has protected long forumId data member, which indicates of course the Topic's forum.

My question is what annotation to use for this data member?

nbro
  • 15,395
  • 32
  • 113
  • 196
socksocket
  • 4,271
  • 11
  • 45
  • 70

3 Answers3

51

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
@JoinColumn(name = "forumId")
private Forum forum;

See more:

ManyToOne and JPA mapping

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
  • 18
    but the "problem" in this case is that when you serialize your Topic to XML or JSON (to pass it to a client, for example), the whole Forum object will also be serialized by default... same thing if you upload a topic to your server, you need to pass the whole Topic+Forum objects, you cannot just use the forum id. In some cases, it seems easier to just manually insert the foreign key of the related entity. – splinter123 Sep 09 '14 at 22:45
  • 1
    How to solve only the forumId in your example/case?? – stallion Aug 12 '18 at 09:08
  • 1
    @stallion if you configure lazy initialization, you will get only the id (no join required) if you only do `getForum().getId()`. See: https://stackoverflow.com/questions/32220951/just-getting-id-column-value-not-using-join-in-hibernate-object-one-to-many-rela/32223785#32223785 – Elias Dorneles Aug 13 '18 at 11:00
5

As others have answered -
You should use the ManyToOne , and JoinColumn annotations.
Bare in mind , that since JPA is about ORM - Object relational mapping,
You should reference another object as you would have done "naturally" in Java - i.e via an object and not via its identifier (which is forumId) in your case),
This was one of the design consideration between the relations at JPA and Hibernate (previously to JPA).

Michael Lihs
  • 7,460
  • 17
  • 52
  • 85
Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27
1

@ManyToOne As the annotation implies - you have many topics per forum

Michael Lihs
  • 7,460
  • 17
  • 52
  • 85
munyengm
  • 15,029
  • 4
  • 24
  • 34