ORMLite。如何建立两个相关的表的一对一关系,比如"外键的主键"

时间:2018-01-31 14:26:21

标签: java postgresql orm ormlite

我有两个表,其中一个表与另一个表的关系超过外来ID到主要ID。

我有一些模型描述,在我看来看起来是正确的,但它没有用。

第一张表

public class Person {
    @DatabaseField(id = true)
    private int id;
    @DatabaseField(columnName = "person_id", foreign = true, foreignAutoRefresh = true)
    Patient patient;

    public Patient getPatient() {
        return patient;
    }

第二张表

 public class Patient {
    @DatabaseField(columnName = "person_id", foreign = true)
    private Person personId;

当我尝试从"患者"通过" Person",我得到一个空指针。 如果亲自更改外键列名,我会得到PSQLException,因为ResultSet不包含这样的列。

对于调试,我使用简单的主方法

public static void main(String[] args) throws SQLException {
    Person p = new PersonDAO().getByUserId();
    System.out.println(p.getPatient());
}

Tables

1 个答案:

答案 0 :(得分:0)

  

如何建立两个相关的表的一对一关系,如“外键的主键”

1对1关系的问题在于Person表格中有patientId字段,而Patient表格中有personId字段。但只有在数据库中创建ID时才会设置ID。

这意味着您将不得不进行3次数据库操作:

  • 通过调用Person在数据库中创建personDao.create(...)以获取与之关联的ID。
  • 在相应的Person上设置Patient,然后使用Patient在数据库中创建patientDao.create(...)
  • 现在,Patient实体将Person设置回患者身份,然后使用personDao.update(...)在数据库中进行更新。

其他一些事情:

  • 我假设您在帖子中错过了dao.getByUserId()方法的参数,因为它需要一个id才能找到有问题的那个。
  • 我认为Patient有一个id字段,即使你没有在帖子中显示它。
  • Patient中的字段应为person,而不是personId。 ORMLite将在该字段中存储id。 Person中的字段正确称为patient

希望这有帮助。

相关问题