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?
Implementing With a Foreign Key in JPA. Note that we place the @OneToOne annotation on the related entity field, Address. Also, we need to place the @JoinColumn annotation to configure the name of the column in the users table that maps to the primary key in the address table.
@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.
Annotation Type JoinColumn. Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply. (Optional) The SQL fragment that is used when generating the DDL for the column.
@Column annotation is used for Adding the column the name in the table of a particular MySQL database.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With