Byron Voorbach
Byron Voorbach

Reputation: 4495

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!

Upvotes: 7

Views: 11403

Answers (2)

Bruce Lowe
Bruce Lowe

Reputation: 6213

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;
}

Upvotes: 10

NimChimpsky
NimChimpsky

Reputation: 47310

Change it to this :

public long getSchool() {
    return this.school;
}

public void setSchool(School school) {
    this.school = school;
}

Upvotes: 0

Related Questions