简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM