I'm working on a hibernate, spring project to help me understand the basics of those two. I'm running into a problem where i want to be able to add foreign keys to my tables.
I've been browsing the internet for information regarding this subject and I haven't been able to find something that suits my needs.
I have two classes:
Schools
Classes
Now i want to map the primary key from Schools to Classes.
This is the code I have now:
@ManyToOne
@JoinColumn(name = "SCHOOL_ID", table = "SCHOOL")
private School school;
and for my getter and setter:
public long getSchool() {
return school.getId();
}
public void setSchool(long schoolId) {
this.school.setId(schoolId);
}
Is this the way to go? Or am I totally looking at it the wrong way.
Thanks!
In this post, we feature a comprehensive Example on Hibernate Foreign Key. Foreign key refers to single column or group of columns in table that link data present in another table through its primary key. A Foreign key can't exist without its parent key but viceversa is not true. Example – A Menu can have submenus.
You can use JPA's @MapsId annotation to tell Hibernate that it shall use the foreign key of an associated entity as the primary key. Let's take a look at a simple example. Each Book has a Manuscript, and each Manuscript belongs to 1 Book. The foreign key of the Book is also the primary key of the Manuscript.
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.
you are on the right track, although its better to deal with the actual objects and not the ids e.g.
@ManyToOne
@JoinColumn(name = "SCHOOL_ID", table = "SCHOOL")
private School school;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school=school;
}
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