我尝试使用新的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();
}
我收到以下错误
...error: Cannot figure out how to read this field from a cursor.
与:
有关 private java.util.List<?> pets;
我想指出,我发现他们的文档中的某些内容确实令人困惑。例如缺少@PrimaryKey
以及User
类缺少@Entity
注释的事实,尽管它应该是一个实体(就像我看到的那样) )。有没有人遇到同样的问题?非常感谢提前
答案 0 :(得分:127)
Document真的令人困惑。试试下面的课程:
1)用户实体:
@Entity
public class User {
@PrimaryKey
public int id; // User id
}
2)宠物实体:
@Entity
public class Pet {
@PrimaryKey
public int id; // Pet id
public int userId; // User id
public String name;
}
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;
*/
}
parentColumn
是指嵌入式User
表的id
列,entityColumn
是指Pet
表的userId
(User
- Pet
关系)列,entity
是指与Pet
表格有关系的表格(User
)。4)UserDao Dao:
@Dao
public interface UserDao {
@Query("SELECT * FROM User")
public List<UserWithPets> loadUsersWithPets();
}
现在尝试loadUsersWithPets()
,它会向用户返回他们的宠物列表。
修改:查看我的other answer以了解多种关系。