Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate, Spring and foreign keys

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!

like image 228
Byron Voorbach Avatar asked Apr 23 '12 14:04

Byron Voorbach


People also ask

What is foreign key in Hibernate?

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.

What is primary key and foreign key in Hibernate?

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.

How foreign key is defined in JPA entity?

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.


1 Answers

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;
}
like image 98
Bruce Lowe Avatar answered Oct 08 '22 01:10

Bruce Lowe