如何从Room数据库
中获取包含别名的Query中的数据因为我们在Entity中获取只返回对象形式的数据的数据所以我们如何从Query中获取数据
SELECT *,(select count(uid) from UserTest) AS rec_count FROM UserTest
即。此字段数据rec_count
获得解决方案
-
第1步
首先创建新的Pojo类,在其中编写实体中编写的所有getter和setter,并为计数值包含int getter和setter
实体类: UserTest.java
@Entity
public class UserTest {
@PrimaryKey(autoGenerate = true)
private int uid;
@ColumnInfo(name = "username")
private String uname;
@ColumnInfo(name = "image_url")
private String imageUrl;
@ColumnInfo(name = "date")
@TypeConverters({DateConverter.class})
private Date DATE;
public UserTest() {
}
@Ignore
public UserTest(int uid) {
this.uid = uid;
}
@Ignore
public UserTest(String uname, String imageUrl, Date DATE) {
this.uname = uname;
this.imageUrl = imageUrl;
this.DATE = DATE;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Date getDATE() {
return DATE;
}
public void setDATE(Date DATE) {
this.DATE = DATE;
}
}
新的Pojo类: Result.java
public class Result {
private int rec_count;
private int uid;
private String username;
private String image_url;
@TypeConverters({DateConverter.class})
private Date date;
public Result() {
}
public Result(int uid) {
this.uid = uid;
}
public Result(String uname, String imageUrl, Date DATE) {
this.username = uname;
this.image_url = imageUrl;
this.date = DATE;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getRec_count() {
return rec_count;
}
public void setRec_count(int rec_count) {
this.rec_count = rec_count;
}
}
第2步:然后在我的Dao类中,即UserDaoTest.java
维护查询并将返回类型设置为
List<Result>
即
@Query("SELECT *,(select count(uid) from UserTest) AS rec_count FROM UserTest")
List<Result> getAllUsersData();
这对我有用!
解释
每当我们在dao @Query anotation
中编写查询时在查询中是否有*它在你的返回pojo中找到所有列名,所以我们应该将它们全部包含在你的返回pojo中
并且为了获取别名中的数据,我们还应该在返回Pojo类中包含在别名上命名的getter和setter变量
希望此信息对其他人也有帮助!