And*_*oro 32 sqlite android android-room android-architecture-components
我正在尝试使用新的Android Persistence Room Library在两个数据库表之间创建关系.我查看了文档,并尝试实现https://developer.android.com/reference/android/arch/persistence/room/Relation.html上的示例:
@Entity
public class User {
@PrimaryKey
int id;
}
@Entity
public class Pet {
@PrimaryKey
int id;
int userId;
String name;
}
@Dao
public interface UserDao {
@Query("SELECT * from User")
public List<User> loadUser();
}
@Dao
public interface PetDao {
@Query("SELECT * from Pet")
public List<Pet> loadUserAndPets();
}
public class UserAllPets {
@Embedded
public User user;
@Relation(parentColumn = "user.id", entityColumn = "userId", entity = Pet.class)
public List pets;
}
@Dao
public interface UserPetDao {
@Query("SELECT * from User")
public List<UserAllPets> loadUserAndPets();
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
...error: Cannot figure out how to read this field from a cursor.
Run Code Online (Sandbox Code Playgroud)
和---关联:
private java.util.List<?> pets;
Run Code Online (Sandbox Code Playgroud)
我想指出,我发现他们的文档中的一些内容确实令人困惑.例如缺少@PrimaryKey
和User
缺少@Entity
注释的事实,尽管它应该是一个实体(就像我看到的那样).有没有人遇到同样的问题?非常感谢提前
Dev*_*rim 140
文件真的很混乱.尝试使用以下课程:
1)用户实体:
@Entity
public class User {
@PrimaryKey
public int id; // User id
}
Run Code Online (Sandbox Code Playgroud)
2)宠物实体:
@Entity
public class Pet {
@PrimaryKey
public int id; // Pet id
public int userId; // User id
public String name;
}
Run Code Online (Sandbox Code Playgroud)
3)UserWithPets POJO:
// Note: No annotation required at this class definition.
public class UserWithPets {
@Embedded
public User user;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
public List<Pet> pets; // or use simply 'List pets;'
/* Alternatively you can use projection to fetch a specific column (i.e. only name of the pets) from related Pet table. You can uncomment and try below;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class, projection = "name")
public List<String> pets;
*/
}
Run Code Online (Sandbox Code Playgroud)
parentColumn
是指嵌入式User
表格的id
列,entityColumn
指的是Pet
表的userId
(User
- Pet
关系)列,entity
指的是与表Pet
有关系的table()User
.4)UserDao Dao:
@Dao
public interface UserDao {
@Query("SELECT * FROM User")
public List<UserWithPets> loadUsersWithPets();
}
Run Code Online (Sandbox Code Playgroud)
现在尝试loadUsersWithPets()
,它返回用户的宠物列表.
编辑:看到我的其他答案很多很多关系.