Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: foreign key annotation

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?

like image 952
socksocket Avatar asked Aug 10 '12 16:08

socksocket


People also ask

How does JPA define foreign key?

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.

What is the use of @entity annotation?

@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.

What is the use of @JoinColumn annotation?

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.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.


2 Answers

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

like image 156
Elias Dorneles Avatar answered Sep 28 '22 05:09

Elias Dorneles


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).

like image 43
Yair Zaslavsky Avatar answered Sep 28 '22 03:09

Yair Zaslavsky