Search code examples
androidspring-bootormandroid-sqliteandroid-room

Get data joining two table in room having same column id


Hi I am using two table student and student_address having common column id as uid in both table(that can't be changed in any condition)

I am using class StudentAndAddress as

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

}

and query i am using as:

@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);

I am getting value of first table but not getting value of second table. In database both table are there


Solution

  • In room we need to solve this type of queries using relation

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

    and query we need to write is:-

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