[go: up one dir, main page]

Skip to content
forked from agrosner/DBFlow

A blazing fast, powerful, and very simple ORM android database library that writes database code for you.

License

Notifications You must be signed in to change notification settings

Weststreet/DBFlow

 
 

Repository files navigation

Android Weekly Android Arsenal Raizlabs Repository

DBFlow

A robust, powerful, and very simple ORM android database library with annotation processing.

The library eliminates the need for writing most SQL statements, writing ContentValues for every table, converting cursors into models, and so much more.

Let DBFlow make SQL code flow like a steady stream so you can focus on your complex problem and not be hindered by repetitive code writing.

This library is based on Active Android, Schematic, Ollie, and Sprinkles, but takes the best of each while offering much more functionality and extensibility.

What sets this library apart:

  1. Every feature has been unit tested to ensure functionality.
  2. Built on maximum performance using annotation processing, lazy-loading, and speed-tests here
  3. Powerful and fluid SQL-wrapping statements
  4. Triggers, Views, Indexes, and many more SQLite features.
  5. Baked-in support for multiple databases seamlessly
  6. ModelContainer classes that enable direct to database parsing for data such as JSON
  7. Rich interface classes that enable powerful flexibility.
  8. ContentProvider generation using annotations

Applications That Use DBFlow

If you wish to have your application featured here, please file an issue.

  1. Anonymous 1: An application that has over 1.5 million active installs
  2. Anonymous 2: An application that will have over 1 million active installs

Changelog

1.7.1

  1. Fixes issue where an IndexMigration recursively called the database rather than use the method database.
  2. Fixes issue where non-unique columns with specified uniqueGroups did not create the groups
  3. Fixes issue where Long or Integer primary keys caused a NullPointerException

1.7.0

  1. Added unique columns support by using @UniqueGroup for columns to enable multiple different groups of columns #117
  2. Fixes an issue where autoincrement update methods do not pass in the id of the object, possibly touching other rows unintentionally
  3. Added global configurable defaults for insertConfict() and updateConflict()in a @Database for any table that does not define a ConflictAction #104
  4. Added bulkInsert support to the @ContentProvider and corresponding method in ContentUtils #108
  5. Added Kotlin support! just change the generatedClassSeparator() for a @Database to Kotlin compatible. #90
  6. Added usage guide for databases
  7. Adds better null loading, as in it prevents loading null values into the object when it's not null. #128

for older changes, from other xx.xx versions, check it out here

Usage Docs

For more detailed usage, check out these sections:

Content Provider Generation

Conditions

Creating Tables and Database Structure

Powerful Model Caching

Migrations

Model Containers

Observing Models

SQL Statements Using the Wrapper Classes

Tables as Lists

Transactions

Type Converters

Triggers, Indexes, and More

Screencasts

Listed here are tutorial screen casts for DBFlow. If more are created, they may go into the usage docs.

  1. DFlow-Installing by @tsuharesu

Including in your project

Gradle

Add the maven repo url to your root build.gradle in the buildscript{} and allProjects{} blocks:

  buildscript {
    repositories {
        maven { url "https://raw.github.com/Raizlabs/maven-releases/master/releases" }
    }
    dependencies {
      classpath 'com.raizlabs:Griddle:1.0.3'
      classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
  }
  
  allprojects {
    repositories {
        maven { url "https://raw.github.com/Raizlabs/maven-releases/master/releases" }
    }
  }

Add the library to the project-level build.gradle, using the apt plugin to enable Annotation Processing and the Griddle plugin to simplify your build.gradle and link sources:

  apply plugin: 'com.neenbedankt.android-apt'
  apply plugin: 'com.raizlabs.griddle'

  dependencies {
    apt 'com.raizlabs.android:DBFlow-Compiler:1.7.1'
    mod "com.raizlabs.android:{DBFlow-Core, DBFlow}:1.7.1"
  }

or by standard Gradle use (without linking sources support):

  apply plugin: 'com.neenbedankt.android-apt'

  dependencies {
    apt 'com.raizlabs.android:DBFlow-Compiler:1.7.1'
    compile "com.raizlabs.android:DBFlow-Core:1.7.1"
    compile "com.raizlabs.android:DBFlow:1.7.1"
  }

Eclipse

Not supported as google is no longer supporting it.

Pull Requests

I welcome and encourage all pull requests. It usually will take me within 24-48 hours to respond to any issue or request. Here are some basic rules to follow to ensure timely addition of your request:

  1. Match coding style (braces, spacing, etc.) This is best achieved using CMD+Option+L (Reformat code) on Mac (not sure for Windows) with Android Studio defaults.
  2. If its a feature, bugfix, or anything please only change code to what you specify. DO NOT do this: Ex: Title "Fixes Crash Related to Bug" includes other files that were changed without explanation or doesn't relate to the bug you fixed. Or another example is a non-descriptive title "Fixes Stuff".
  3. Pull requests must be made against develop branch.
  4. Have fun!

Configuration

We need to configure the FlowManager properly. Instead of passing in a Context wherever it is used, we hold onto the Application context instead and reference it.

You will need to extend the Application class for proper configuration:

public class ExampleApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FlowManager.init(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        FlowManager.destroy();
    }
}

Lastly, add the definition to the manifest (with the name that you chose for your custom application):

<application
  android:name="{packageName}.ExampleApplication"
  ...>
</application>

First class you need to define is the @Database. It is recommended you store the name and version as static final fields. The database name is not required for singular databases, however it is good practice to include it here.

@Database(name = AppDatabase.NAME, version = AppDatabase.VERSION, foreignKeysSupported = true)
public class AppDatabase {

    public static final String NAME = "App";

    public static final int VERSION = 1;
}

Second, you need to define at least one @Table class. The databaseName is only required when dealing with multiple databases. You can either implement the Model interface or extend BaseModel.

@Table(databaseName = TestDatabase.NAME)
public class TestModel1 extends BaseModel {
    @Column(columnType = Column.PRIMARY_KEY)
    public
    String name;
}

Prepackaged Databases

So you have an existing DB you wish to include in your project. Just name the database the same as the database to copy, and put it in the app/src/main/assets/ directory.

Migrations

in DBFlow migrations are separate, public classes that contain both the @Migration and Migrationinterface. If you are using multiple databases, you're required to specify it for the migration. For more information, check it out here

@Migration(version = 2, databaseName = TestDatabase.NAME)
public class Migration1 extends BaseMigration {

    @Override
    public void onPreMigrate() {
      // called before migration, instantiate any migration query here
    }

    @Override
    public void migrate(SQLiteDatabase database) {
      // call your migration query
    }

    @Override
    public void onPostMigrate() {
      // release migration resources here
    }
}

Basic Query Wrapping

The SQL language is wrapped in a nice builder notation. DBFlow generates a $Table containing static final column strings to use in your queries!

new Select().from(DeviceObject.class)
                             .where(Condition.column(DeviceObject$Table.NAME).eq("Samsung-Galaxy S5"))
                             .and(Condition.column(DeviceObject$Table.CARRIER).eq("T-MOBILE"))
                             .and(Condition.column(DeviceObject$Table.LOCATION).eq(location);

To see more go to the full tutorial

Model Containers

Model containers are classes that imitate and use the blueprint of Model classes in order to save data such as JSON, Hashmap, or your own kind of data to the database. To create your own, extend the BaseModelContainer class or implement the ModelContainer interface. More info here

For example here is the JSONModel implementation:

public class JSONModel<ModelClass extends Model> extends BaseModelContainer<ModelClass, JSONObject> implements Model {

    public JSONModel(JSONObject jsonObject, Class<ModelClass> table) {
        super(table, jsonObject);
    }

    public JSONModel(Class<ModelClass> table) {
        super(table, new JSONObject());
    }

    @Override
    @SuppressWarnings("unchecked")
    public BaseModelContainer getInstance(Object inValue, Class<? extends Model> columnClass) {
        return new JSONModel((JSONObject) inValue, columnClass);
    }

    @Override
    public JSONObject newDataInstance() {
        return new JSONObject();
    }

    @Override
    public Object getValue(String columnName) {
        return getData().opt(columnName);
    }

    @Override
    public void put(String columnName, Object value) {
        try {
            getData().put(columnName, value);
        } catch (JSONException e) {
            FlowLog.logError(e);
        }
    }
}

And then in every Model class you wish to use this class, you need to add the annotation @ContainerAdapter. This generates the definition required to save objects correctly to the DB.

Type Converters

TypeConverter allows non-Model objects to save to the database by converting it from its Model value to its Database value. These are statically allocated accross all databases. More info here

@com.raizlabs.android.dbflow.annotation.TypeConverter
public class CalendarConverter extends TypeConverter<Long, Calendar> {

    @Override
    public Long getDBValue(Calendar model) {
        return model.getTimeInMillis();
    }

    @Override
    public Calendar getModelValue(Long data) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(data);
        return calendar;
    }
}

Model Views

ModelView are a special kind of Model that creates a database VIEW based on a special SQL statement. They must reference another Model class currently. More info here

@ModelView(query = "SELECT * FROM TestModel2 WHERE model_order > 5", databaseName = TestDatabase.NAME)
public class TestModelView extends BaseModelView<TestModel2> {
    @Column
    long model_order;
}

Maintainers

agrosner (@agrosner)

Contributors

wongcain

mozarcik

mickele

intrications

mcumings

About

A blazing fast, powerful, and very simple ORM android database library that writes database code for you.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 100.0%