gpt4 book ai didi

java - Android Room - 处理对象中的对象列表和查询结果

转载 作者:可可西里 更新时间:2023-11-01 07:55:46 25 4
gpt4 key购买 nike

我在使用 Android 的房间数据库,但在理解如何执行以下操作时遇到了一些大问题:

  1. 当我添加 Person到数据库,它添加所有变量,例如List<Shoe> , List<Pet>等到数据库。
  2. 创建关系,以便在我检索 Person 时,它的所有字段都被检索,例如 Pet, Shoe, Shirt等等(不确定是什么类型的查询)

  3. 执行简单查询,例如Retrieve Person where鞋名= "boot" ;

我知道您必须对对象列表使用外键关系,否则对于单个对象可以使用 @Embed@TypeConverter

示例代码如下;

@Entity(tableName = "person")
public class Person {
@PrimaryKey
@NonNull
private String personId;
private List<Pet> pets;
private List<Shoe> shoes;
private List<Shirt> shirts;
}

@Entity(foreignKeys = {
@ForeignKey(
entity = Person.class,
parentColumns = "personId",
childColumns = "personIdFk"
)
})
public class Pet {
String petId;
String name;
String personIdFk; //Foreign key to person
}

@Entity(foreignKeys = {
@ForeignKey(
entity = Person.class,
parentColumns = "personId",
childColumns = "personIdFk"
)
})
public class Shoe {
String shoeId;
String name;
String personIdFk; //Foreign key to person
}


@Entity(foreignKeys = {
@ForeignKey(
entity = Person.class,
parentColumns = "personId",
childColumns = "personIdFk"
)
})
public class Shirt {
String shirtId;
String name;
String personIdFk; //Foreign key to person
}

最佳答案

由于某些 potential issues with lazy loading,Room 不直接支持此功能,但有一些 DAO 技巧是可能的。您需要显式处理插入,并立即查询所有内容,您需要一个 POJO 来包装所有内容。

@Entity(foreignKeys = {
@ForeignKey(
entity = PersonEntity.class,
parentColumns = "personId",
childColumns = "personIdFk",
onDelete = CASCADE
)
})
public class Pet {
@PrimaryKey
private String petId;
private String name;
private String personIdFk;
}

@Entity(tableName = "person")
public class PersonEntity {
@PrimaryKey
private String personId;
}

public class Person {
@Embedded
private PersonEntity personEntity;
@Relation(parentColumn = "personId", entityColumn = "personIdFk")
private List<Pet> pets;
}

@Dao
public abstract class PersonDao {

@Insert
protected abstract void insert(PersonEntity personEntity);

@Insert
protected abstract void insert(List<Pet> pets);

@Transaction
public void insert(Person person) {
insert(person.getEntity());
insert(person.getPets());
}

@Query("SELECT * FROM person")
public abstract List<Person> getAll();

}

@Database(entities = {PersonEntity.class, Pet.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

public abstract PersonDao personDao();

}

为简洁起见省略了构造函数、getter 和 setter。

关于java - Android Room - 处理对象中的对象列表和查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47753396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com