hellzone
hellzone

Reputation: 5246

How to get foreignkey value

I have tables named Student and School. My Student table columns are (studentName,studentNumber and school_id_fkey). My Student entity looks like;

public Class Student{

 String studentName;

 String studentNumber;

 @JoinColumn(name = "school_id_fkey", referencedColumnName = "id")
 School school;
 ....
}

What I want to do is I want to get specific student's school id. When I try below code it gets School object but I just want to get school id. Is there any way to do this?

student.getSchool();

Upvotes: 0

Views: 48

Answers (1)

Augusto
Augusto

Reputation: 29997

There's no perfect way to do this, but the pattern is to map the column twice: once for the object (as you have in your question) and another time with the id value. The id value should be marked as read only otherwise hibernate throws an error.

The drawback of this approach is that if you assign a new school to a student, the id value won't change until you read the student object back from the DB.

@JoinColumn(name = "school_id_fkey", referencedColumnName = "id")
School school;

@Colum(name = "school_id_fkey", insertable= false, updatable= false)
long schoolId;

Please don't take the above code as an exact good example, as I haven't tested it nor have a bit of code that does this in the projects I'm working ATM.

Upvotes: 2

Related Questions