Reputation: 11
I have two tables, one of them have relations with another over foreign id to primary id.
And I have some model description, which in my opinion looks correct, but it doesn't work.
First table
public class Person {
@DatabaseField(id = true)
private int id;
@DatabaseField(columnName = "person_id", foreign = true, foreignAutoRefresh = true)
Patient patient;
public Patient getPatient() {
return patient;
}
Second table
public class Patient {
@DatabaseField(columnName = "person_id", foreign = true)
private Person personId;
When I try to find data from "Patient" over the "Person", I get a null pointer. If change foreign key column name in person, I get PSQLException, because ResultSet does not contain such a column.
For debugging, I use simple main method
public static void main(String[] args) throws SQLException {
Person p = new PersonDAO().getByUserId();
System.out.println(p.getPatient());
}
Upvotes: 1
Views: 293
Reputation: 116888
How to establish one-to-one relations of two tables related, like “primary key to foreign key”
The problem with the 1-to-1 relationship is that in the Person
table there is a patientId
field and in the Patient
table there is a personId
field. But the ids only get set when they are created in the database.
This means that you will have to do 3 database operations:
Person
in the database to get an ID associated with it by calling personDao.create(...)
.Person
on the corresponding Patient
, then create the Patient
in the database with patientDao.create(...)
.Patient
back on the Person
entity now that the patient has has an id, then update it in the database with personDao.update(...)
.Couple of other things:
dao.getByUserId()
method in your post since it needs an id to find the particular one in question.Patient
has an id field even though you don't show it in your post.Patient
should be just person
, not personId
. ORMLite will store an id in that field under the covers. The field in Person
is correctly called patient
.Hope this helps.
Upvotes: 1