我有一个看起来像下面的表格
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Product
{
@PrimaryKey
@ColumnInfo(name = "ID")
@JsonProperty("ID")
public int id;
@ColumnInfo(name = "Name")
@JsonProperty("Name")
public String name;
@ColumnInfo(name = "Documents")
@JsonProperty("Documents")
@TypeConverters(DocumentConverter.class)
public List<Document> documents;
}
//...
@TypeConverters(DocumentConverter.class)
@JsonIgnoreProperties( ignoreUnknown = true )
@JsonTypeName("Documents")
public class Document
{
@JsonProperty("Name")
public String name;
@JsonProperty("URL")
public String url;
}
我可以通过执行以下操作根据其名称检索产品
@Query("SELECT * FROM Product WHERE Name = :name")
List<Product> getProducts(String name);
然后,我将能够访问每个 Product 对象的文档列表。但是,我也只想处理具有某些文档的产品。我可以通过上述查询获取所有产品,然后手动过滤我想要的文档,但是当我只查找非常具体的文档时,这变得非常痛苦。
是否可以基于文档变量进行查询,而不是单独的表?
像...
@Query("SELECT * FROM Product WHERE Name = :name AND Document.name = :documentName")
List<Product> getProducts(String name, String documentName);
谢谢。
您可以使用LIKE sql 语句在 json 列内搜索转换后的文档列表。例: 假设我们有这样的文档转换以存储在数据库中:
{
name: "Title",
url: "Your_url"
}
因此,您对列表中包含此类文档的产品的查询应如下所示:
SELECT * FROM Product WHERE Name = :name AND Documents LIKE :documentLikeExpr
哪里
String documentLikeExpr = "%name: "Title"%";
表达式中的 % 表示零、一个或多个字符。
所以我们在这里唯一要做的就是使用 SQL 语言功能在列内搜索部分字符串。
不能查询文档类变量,因为它未存储为单独的表。@TypeConverter批注将文档列表转换为某些预定义的数据类型,如字符串。基本上它将文档列表作为字符串Gson存储在产品表的一列中,因此我们无法像Document.name那样在SQL查询中访问文档类的字段名称。
在此处阅读@CommonsWare给出的选项 #2
因此,要访问它,您必须为文档创建一个单独的表。