Hibernate, Spring and foreign keys

10,777

Solution 1

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

Solution 2

Change it to this :

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

public void setSchool(School school) {
    this.school = school;
}
Share:
10,777
Byron Voorbach
Author by

Byron Voorbach

Search & Data Engineer working for Luminis Amsterdam. Certified Ethical Hacker Elastic Enthousiast

Updated on June 13, 2022

Comments

  • Byron Voorbach
    Byron Voorbach almost 2 years

    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!