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

Not able to get query results using Room persistence

我正在使用 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 class,如下所示:

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 不同class。应该是一样的。或者,您可以使用 @ColumnInfo 注释将 Pojo 变量映射到列名。

例如,

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

这样,id 将映射到 user_id

更改您的查询:

@Query("SELECT * FROM users JOIN cars ON users.id = cars.userId")

指定 POJO 中的列 classUserWithCar。返回的列必须匹配所有列,并且与您的 POJO 具有相同的列名。您可以使用 AS 更改查询中的列名。

@Query("SELECT userId as userId , brand as brand FROM users JOIN cars ON users.id = cars.userId")

或者,您可以使用@ColumnInfo 指定列名映射。