Pavel Rodionov
Pavel Rodionov

Reputation: 11

ORMLite. How to establish one-to-one relations of two tables related, like "primary key to foreign key"

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

Tables

Upvotes: 1

Views: 293

Answers (1)

Gray
Gray

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:

  • Create the Person in the database to get an ID associated with it by calling personDao.create(...).
  • Set the Person on the corresponding Patient, then create the Patient in the database with patientDao.create(...).
  • Set the 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:

  • I assume you are missing an argument to the dao.getByUserId() method in your post since it needs an id to find the particular one in question.
  • I assume that Patient has an id field even though you don't show it in your post.
  • The field in the 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

Related Questions