Android Room数据库多表查询的使用实例数据库多表查询的使用实例
主要介绍了Android Room数据库多表查询的使用实例,小编觉得挺不错的,现在分享给大家,也给大家做个参
考。一起跟随小编过来看看吧
Android-Room数据库(介绍)
前言前言
在SQLite数据库中,我们可以指定对象之间的关系,因此我们可以将一个或多个对象与一个或多个其他对象绑定。这就是所
谓的一对多和多对多的关系。
既然要多表查询,所以表之间就得有关联。这时候我们就得使用新的注解符@ForeignKey
接下来的内容,就需要上节的内容了
@Entity
public class Company {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private int age;
private String address;
private double salary;
public Company(String name, int age, String address, double salary) {
this.name = name;
this.age = age;
this.address = address;
this.salary = salary;
}
//省略了getter/setter方法
}
下面我们再新建一个与之关联的表
@Entity(foreignKeys = @ForeignKey(entity = Company.class,parentColumns = "id",childColumns = "emp_id",onDelete = CASCADE),
indices = @Index(value={"emp_id"},unique = true))
public class Department {
@PrimaryKey(autoGenerate = true)
private int id;
private String dept;
@ColumnInfo(name = "emp_id")
private int empId;
public Department(String dept, int empId) {
this.dept = dept;
this.empId = empId;
}
//省略了getter/setter方法
}
这里我使用了@ForeignKey关联了company表,主键id,外键emp_id,紧接着使用了indices创建了唯一索引。
下面就是创建Dao
@Dao
public interface CompanyDao {
@Query("SELECT * FROM company")
List<Company> getAllCompany();
}
@Dao
public interface DepartmentDao {
@Query("SELECT * FROM department")
List<Department> getAllDepartment();
//使用内连接查询
@Query("SELECT emp_id,name,dept from company INNER JOIN department ON Company.id=Department.emp_id")
List<InnerJoinResult> getDepartmentFromCompany();
}
最后就是创建Database
@Database(entities = {Department.class, Company.class}, version = 1, exportSchema = false)
public abstract class DepartmentDatabase extends RoomDatabase {
评论0