2019 Android 数据库DbFlow的使用

提前了解:
DBFlow是一个用于Android的SQLite库,它使得交互和使用数据库变得非常容易。使用注释处理构建,为您生成大部分样板代码,DB中的代码使用快速,高效且类型安全。它消除了繁琐(并且难以维护)的数据库交互代码。
官文 :https://agrosner.gitbooks.io/dbflow/content/
github: https://github.com/agrosner/DBFlow

使用:

  1. 导入引入DBflow库
allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven { url "https://jitpack.io" }
        google()
    }
}
  dependVersion = [
          support: "26.1.0",
          dbflow : "4.2.4"
        ]

   //DBFLOW
  "dbflow-processor"    : "com.github.Raizlabs.DBFlow:dbflow-processor:${dependVersion.dbflow}",
  "dbflow-core"         : "com.github.Raizlabs.DBFlow:dbflow-core:${dependVersion.dbflow}",
  "dbflow"              : "com.github.Raizlabs.DBFlow:dbflow:${dependVersion.dbflow}",
  "dbflow-sqlcipher"    : "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${dependVersion.dbflow}",
  1. 在Application中初始化Dbflow
public class MyApp extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    FlowManager.init(this);
  }
}
  1. 创建数据库
@Database(name = AppDatabase.NAME, version = AppDatabase.VERSION)
public class AppDatabase {

  public static final String NAME = "AppDatabase";

  public static final int VERSION = 1;
}

该@Database注解生成一个DatabaseDefinition现在名为“AppDatabase.db”的文件中引用磁盘上的SQLite数据库。您可以在代码中引用它:

DatabaseDefinition db = FlowManager.getDatabase(AppDatabase.class);
  1. 创建表格
@Table(database = AppDatabase.class)
public class User {

  @PrimaryKey // at least one primary key required
  UUID id; 

  @Column
  String name;

  @Column
  int age;
}
  1. 创建,读取,更新和删除模型
User user = new User();
user.id = UUID.randomUUID();
user.name = "Andrew Grosner";
user.age = 27;

ModelAdapter adapter = FlowManager.getModelAdapter(User.class);
adapter.insert(user);

user.name = "Not Andrew Grosner";
adapter.update(user);

adapter.delete(user); 

// if you extend BaseModel or implement Model
user.insert();
user.update();
user.delete();
user.save();

// find adult users
List users = SQLite.select()
                    .from(User.class)
                    .where(User_Table.age.greaterThan(18))
                    .queryList();

// or asynchronous retrieval
SQLite.select()
  .from(User.class)
  .where(User_Table.age.greaterThan(18))
  .async()
  .queryListCallback((QueryTransaction transaction, @NonNull CursorResult result) -> {
              // called when query returns on UI thread
              try {
                List users = result.toList();
                // do something with users
              } finally {
                result.close();
              }
            })
  .error((Transaction transaction, Throwable error) -> {
              // handle any errors
         })
  .execute();

你可能感兴趣的:(android)