使用房间在"@Query"结果中使用"@Ignore"字段



我有两个简单的locationhouses表。 我希望能够获取包含所有相关信息的location,并将house计数添加到该查询中。houseCount字段标记为@Ignored,因为我不希望保存它。但是,Room 似乎不能像指定为查询的返回对象类型的任何其他类那样使用该字段从查询返回数据。

我的领域:

@Ignore
@ColumnInfo(name = EXTRA_COLUMN_LOCATION_HOUSE_COUNT)
public int houseCount;

我的位置构造函数:

public Location(long id, String name, LatLng location, long defaultRent, Date synced, int houseCount) {...}

我的查询:

SELECT locations.*, COUNT(DISTINCT houses.id) AS house_count FROM locations, houses WHERE locations.id = :id AND houses.location_id = :id

警告:

Warning:(37, 14) The query returns some columns [house_count] which are not use by ug.karuhanga.logrealty.Models.Entities.Location. You can use @ColumnInfo annotation on the fields to specify the mapping.  You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, name, location, default_rent, synced, house_count. Fields in ug.karuhanga.logrealty.Models.Entities.Location: id, name, location, default_rent, synced.

和错误:

Error:(33, 8) error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
Tried the following constructors but they failed to match:
Location(long,java.lang.String,ug.karuhanga.logrealty.Utils.LocationUtils.LatLng,long,java.util.Date,int) : [id : id, name : name, location : location, defaultRent : defaultRent, synced : synced, houseCount : null]

有关在房间 db 中@Ignore的解决方法,请参阅此内容。 @Ignore注释的房间数据库生成错误

对于 Kotlin,这对我有用:

1. 将@JvmOverloads添加到您的数据类中,如下所示:

@Entity(tableName = "student")
data class Student @JvmOverloads constructor(
...
)

2. 将@PrimaryKey字段放在构造函数的末尾,如下所示:

@Entity(tableName = "student")
data class Student @JvmOverloads constructor(    
var name: String,            
var age: Int,                 
var gpa: Double,
var isSingle: Boolean,
@Ignore                            
var isSelected: Boolean = false,      
@PrimaryKey(autoGenerate = true)        //must be placed at the end!!
var id: Long = 0                        
)

也许很晚,因为这篇文章是在 2020 年完成的,但我搜索了很多解决方案。 终于找到了这篇文章,但无法将其翻译成 Java,所以不得不提出我自己的解决方案。 有更好的解决方案,但我找不到它们,所以在我的解决方案下面,希望它能帮助其他人。

我想这样做。

@Query("SELECT tableA.*, " +
"(SELECT COUNT(*) FROM tableB WHERE tableB.Id = tableA.Id) AS Counter " +
"FROM tableA")
LiveData<List<MyObject>> getmyObjectLiveData();

为此,我有一个MyObject类,其中包含:

@Ignore
Counter

这导致了与上述相同的警告。 最后,我通过创建第二个对象"MyObject2"解决了它,该对象具有与"MyObject"类相同的字段,但没有没有任何数据库引用(@Entity,@PrimaryKey,@NonNull和@Ignore都被删除)。将计数器字段添加到构造函数中,并将我的实时更新查询结果更改为"MyObject2"。 当然,必须更改许多类,因为回收器视图使用数据,因此,不仅更改了DAO,还更改了存储库,视图模型和适配器以使用此MyObject2类但是工作得很好,没有任何错误/警告

我在 MyObject2 类中添加了一个额外的公共方法,以便轻松检索 MyObject 类版本,因为最终我仍然需要原始 MyObject 来处理插入和更新。 和 MyObject 基本上是 MyObject2 字段的子集

最新更新