【问题标题】:Get data joining two table in room having same column id获取数据加入房间中具有相同列 id 的两个表
【发布时间】:2020-05-06 19:03:37
【问题描述】:

您好,我正在使用两个表 student 和 student_address,在两个表中都有共同的列 id 作为 uid(在任何情况下都不能更改)

我正在使用 StudentAndAddress 类作为

public class StudentAndAddress{

    @Embedded
    private Student student;

    @Embedded(prefix = "type_")
    private StudentAddress studentAddress;

    public Address getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public StudentAddress getStudentAddress() {
        return studentAddress;
    }

    public void setStudentAddress(StudentAddress studentAddress) {
        this.studentAddress = studentAddress;
    }

}

我使用的查询是:

@Query("SELECT * FROM student  INNER JOIN student_address ON student.uid == student_address.address_uid and address_link.linkto_type==:linkToType")
LiveData<List<StudentAndAddress>> getStudentAndAddress(String linkToType);

我得到了第一个表的值,但没有得到第二个表的值。 在数据库中,两个表都存在

【问题讨论】:

    标签: android spring-boot orm android-sqlite android-room


    【解决方案1】:

    我认为,你的问题的根源是前缀,你给你的@Embedded:

    @Embedded(prefix = "type_")
    private StudentAddress studentAddress;
    

    由于该 Room 无法匹配查询结果中的字段名称和类 StudentAndAddress 中的字段。您必须去掉前缀(然后 filelds 的名称将相等)或更改地址表查询中的别名(将前缀添加到它们) - 像这样:

    @Query("SELECT student.*,addresses.[field1] as type_[field1], adsresses.address_uid as type_address_uid, ... FROM student  INNER JOIN student_address as addresses ..."
    

    【讨论】:

      【解决方案2】:

      在房间里,我们需要使用关系来解决这种类型的查询

      public class StudentAndAddress{
      
          @Embedded
          private StudentAddress studentAddress;
      
      
          @Relation(
                  parentColumn = "address_uid",
                  entityColumn = "uid",
                  entity = Student.class
          )
          private Student student;
      
      
          public Address getStudent() {
              return student;
          }
      
          public void setStudent(Student student) {
              this.student = student;
          }
      
          public StudentAddress getStudentAddress() {
              return studentAddress;
          }
      
          public void setStudentAddress(StudentAddress studentAddress) {
              this.studentAddress = studentAddress;
          }
      
      }
      

      我们需要写的查询是:-

      @Query("SELECT * FROM student_address WHERE linkto_type==:linkToType")
      LiveData<List<StudentAndAddress>> getStudentAndAddress(String linkToType);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2014-06-05
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        相关资源
        最近更新 更多