gpt4 book ai didi

android - 无法使用 Room persistence 获取查询结果

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:56 27 4
gpt4 key购买 nike

我正在使用 Room 持久性库开发一个 Android 应用程序。我有一个用户和一个汽车实体

@Entity(tableName = "users")
public class User {

@PrimaryKey
@NonNull
private int id;
private String name;

public User(@NonNull int id, String name) {
this.id = id;
this.name = name;
}
}

@Entity(tableName = "cars", foreignKeys = @ForeignKey(parentColumns  = 
"id", childColumns = "userId", entity = User.class))
public class Car {

@PrimaryKey(autoGenerate = true)
private int id;
private int userId;
private String brand;

public Car(int userId, String brand) {
this.userId = userId;
this.brand = brand;
}
}

我还创建了一个 UserWithCar 类,如下所示:

public class UserWithCar {

@Embedded(prefix = "user_")
public User user;

@Embedded(prefix = "car_")
public Car car;
}

正如您在 UserWithCar 中看到的那样,我使用了前缀,因为如果不这样做,我会收到以下错误:

Multiple fields have the same columnName: id. Field names: user > id, car > id.

我想使用以下查询获取所有 UserWithCar:

@Query("SELECT * FROM users JOIN cars ON users.id = cars.userId")
List<UserWithCar> getUserWithCar();

使用这个查询我得到以下错误:

The query returns some columns [id, name, id, userId, brand] which are not use by com.roomdemo.data.models.UserWithCar. You can use @ColumnInfo annotation on the fields to specify the mapping. com.roomdemo.data.models.UserWithCar has some fields [user_id, user_name, car_id, car_userId, car_brand] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, name, id, userId, brand. Fields in com.foodtec.roomdemo.data.models.UserWithCar: user_id, user_name, car_id, car_userId, car_brand.

我需要一些帮助吗?谢谢!

更新使用@Wizard 帮助,我从@Embeded 中删除了前缀,并为用户 ID 添加了@ColumnInfo“uId”,为汽车 ID 添加了“cId”,以便不具有相同的 id 字段。通过这种方式它可以工作!

最佳答案

Columns returned by the query: id, name, id, userId, brand. Fields in com.foodtec.roomdemo.data.models.UserWithCar: user_id, user_name, car_id, car_userId, car_brand.

错误表明,查询返回的列与 Pojo 类不同。应该是一样的。或者,您可以使用 @ColumnInfo 注释将 Pojo 变量映射到列名。

例如,

@PrimaryKey
@NonNull
@ColumnInfo(name = "user_id")
private int id;

这样,id 将映射到 user_id

关于android - 无法使用 Room persistence 获取查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536865/

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