Property与查询条件

DBFlow中会自动生成与你的Model类相对应的_Table类。其中是将Model类中的属性都转为了PropertyProperty是一种类型安全的处理方式,方便我们使用条件

在SQL中Condition条件语句类似于这样:

name = 'Test'

name = `SomeTable`.`Test`

name LIKE '%Test%'

name != 'Test'

salary BETWEEN 15000 AND 40000

name IN('Test','Test2','TestN')

((`name`='Test' AND `rank`=6) OR (`name`='Bob' AND `rank`=8))

如何描述条件

我们会自动生成条件语句所需要的Property

例如现在我们有一张简单的数据表:

@Table(database = TestDatabase.class, name = "TestModel32")
public class TestModel3 {

    @Column
    @PrimaryKey
    public String name;

    @Column
    String type;
}

这时DBFlow会生成相应的TestModel3_Table类:

public final class TestModel3_Table {
  public static final Property<String> name = new Property<String>(TestModel3.class, "name");

  public static final Property<String> type = new Property<String>(TestModel3.class, "type");

  public static BaseProperty getProperty(String columnName) {
    columnName = QueryBuilder.quoteIfNeeded(columnName);
    switch (columnName)  {
      case "`name`":  {
        return name;
      }
      case "`type`":  {
        return type;
      }
      default:  {
        throw new IllegalArgumentException("Invalid column name passed. Ensure you are calling the correct table's column");
      }
    }
  }
}

这样我们就可以安全、方便地使用Property来描述我们的条件了:

TestModel3_Table.name.is("Test"); // name = 'Test'
TestModel3_Table.name.withTable().is("Test"); // TestModel3.name = 'Test'
TestModel3_Table.name.like("%Test%")

对于Property,我们提供了以下操作符的支持:

  1. is(), eq() -> =
  2. isNot(), notEq() -> !=
  3. isNull() -> IS NULL / isNotNull()IS NOT NULL
  4. like(), glob()
  5. greaterThan(), greaterThanOrEqual(), lessThan(), lessThanOrEqual()
  6. between() -> BETWEEN
  7. in(), notIn()

组合条件ConditionGroup

ConditionGroupConditionQueryBuilder的继任者,但它相比于QueryBuilder是有缺陷的。

ConditionGroup可以作为Condition使用,也可以用于组合其他一些Condition

The ConditionGroup is the successor to the ConditionQueryBuilder. It was flawed in that it conformed to QueryBuilder, yet contained Condition, and required a type-parameter that referenced the table it belonged in.

ConditionGroup are arbitrary collections of Condition that can combine into one SQlite statement or be used as Condition within another ConditionGroup.

Any Sqlite wrapper class that takes in multiple Condition use this class to construct the query for it.

SQLite.select()
  .from(MyTable.class)
  .where(MyTable_Table.someColumn.is("SomeValue"))
  .and(MyTable_Table.anotherColumn.is("ThisValue"));

  // 或者
  SQLite.select()
    .from(MyTable.class)
    .where(ConditionGroup.clause()
      .and(MyTable_Table.someColumn.is("SomeValue")
      .or(MyTable_Table.anotherColumn.is("ThisValue"));