• Stars
    star
    182
  • Rank 211,154 (Top 5 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DAO for SQLBrite

SQLBrite DAO

Build Status

Dependencies

Latest version: Maven Central

// DAO
compile 'com.hannesdorfmann.sqlbrite:dao:xxx'

// Object Mapper
compile 'com.hannesdorfmann.sqlbrite:annotations:xxx'
apt 'com.hannesdorfmann.sqlbrite:object-mapper:xxx'

To run annotation processing you have to use apt. Please note that DAO and Object-Mapper are independent. You can choose whether you want to use both or not.

How to use

This library adds an layer on top of SQLBrite by providing basically two modules:

  1. ObjectMapper
  2. Dao

ObjectMapper

This project doesn't aim to implement a full ORM framework and will never be. It just uses annotation processing to generate code for reading value from Cursor and handle ContentValues. With @Column you specify with database table column belongs to which field of your Model class. You can annotate fields (no private or protected fields are allowed) or public setter methods. With @ObjectMappable you have to annotate your model class containnig @Column annotations like this:

@ObjectMappable
public class Customer {

  public static final String TABLE_NAME = "Customer";
  public static final String COL_FIRSTNAME = "firstname";
  public static final String COL_LASTNAME = "lastname";
  public static final String COL_ID = "id";



  protected long id;
  @Column(COL_FIRSTNAME) String firstname;
  @Column(COL_LASTNAME) String lastname;

  public Customer() {
  }

  public Customer(long id, String firstname, String lastname) {
    this.id = id;
    this.firstname = firstname;
    this.lastname = lastname;
  }

   @Column(COL_ID)
   public void setId(int id) {
    this.id = id;
   }

   public long getId() {
    return id;
   }


  public String getFirstname() {
    return firstname;
  }

  public String getLastname() {
    return lastname;
  }
}

For Customer a class called CustomerMapper gets generated that looks like this:

public final class CustomerMapper {

  /**
   * RxJava Func1 Method that can be used to generate a Customer from a Cursor's data (sql row)
   */
  public static final Func1<Cursor, Customer> MAPPER = new Func1<Cursor, Customer>() {
    ...
  }


  /**
   * Get a typesafe ContentValues Builder
   * @return The ContentValues Builder
   */
  public static ContentValuesBuilder contentValues() {
    ...
  }

}

So basically it generates a Func1 that can be applied on a SQLBrite QueryObservable to instantiate your data object (i.e. Customer) out of a Cursor (cursor gets closed internally and resources released by SQLBrite) and retrieve fetch data by calling cursor.getString(index) and so on. See DAO section below for a concrete example how to use the generated Func1. Additionally, it also generates a type safe builder for ContentValues.

ContentValues cv = CustomerMapper.contentValues()
                        .id(1)
                        .firstname("Hannes")
                        .lastname("Dorfmann")
                        .build();

The supported types for @Column are:

  • String
  • int
  • long
  • short
  • float
  • double
  • boolean
  • byte[]
  • java.util.Date (mapped to long internally, time in milli seconds)

Kotlin support

ObjectMapper is supported by Kotlin (use kapt instead of apt for annotation processing):

 @ObjectMappable
 class People  {

     @Column("name")
     var name: String? = null

     @Column("age")
     var age : Int = 0
 }

Unfortunately, data classes are not supported yet.

Auto-Value

The provided Object Mapper does not support Auto-Value. However, there is a nice library called auto-value-cursor that can be used instead of the build in Object Mapper and with the DAO module to achieve the same, just with auto-value.

DAO

Create your own Data Access Object (DAO) where you define methods to manipulate or query your database table. Usually a DAO represents a database table, like the database table for storing Customer:

public class CustomerDao extends Dao {

  @Override public void createTable(SQLiteDatabase database) {

    CREATE_TABLE(Customer.TABLE_NAME,
        Customer.COL_ID + " INTEGER PRIMARY KEY NOT NULL",
        Customer.COL_FIRSTNAME + " TEXT",
        Customer.COL_LASTNAME + " TEXT")
        .execute(database);

  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion == 1 && newVersion == 2){
      ALTER_TABLE(Customer.TABLE_NAME)
          .ADD_COLUMN(Customer.PHONE_NUMBER +" TEXT")
          .execute(db);
    }
  }


  ...

}

onCreateTable() and onUpgrade() gets called internally (from an internal SQLiteOpenHelper) to create or migrate the table for Customer.

As you already have seen above, the DAO provides provides a high level API so you don't have to deal that much with String concatenation and can use IDE's auto completion to build your sql statements. The same API can be used to create SQL query statements:

public class CustomerDao extends Dao {

  @Override public void createTable(SQLiteDatabase database) {
    ...
  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ...
  }


  public Observable<List<Customer>> getCustomers(String lastname) {
      return query(
        SELECT(Customer.COL_ID, Customer.COL_FIRSTNAME, Customer.COL_LASTNAME)
        .FROM(Customer.TABLE_NAME)
        .WHERE(Customer.COL_LASTNAME + " = ? ")
       )
       .args(lastname) // arguments that replace the "?" placeholders in SQL statement
       .run() // Executes query
       .mapToList(CustomerMapper.MAPPER) // Use the generated Func1 method
      );
    }


    public Observable<Long> addCustomer(int id, String firstname, String lastname) {
      ContentValues values = CustomerMapper.contentValues()
                             .id(id)
                             .firstname(firstname)
                             .lastname(lastname)
                             .build();

      return insert(Customer.TABLE_NAME, values);
    }

}

To register your DAO classes to SQLBrite you have to create a DaoManager. While a Dao represents a table of a database DaoManager represents the whole database file. DaoManager internally creates a SQLiteOpenHelper and instantiates a SqlBrite instance. All DAO's registered to the same DaoManager share the same SqlBrite instance.

CustomerDao customerDao = new CustomerDao();
AddressDao addressDao = new AddressDao();

DaoManager daoManager = DaoManager.with(context)
                                .databaseName("Customers.db")
                                .version(1)
                                .add(customerDao)
                                .add(addressDao)
                                .logging(true)
                                .onTablesCreated(createdListener) // optional callback
                                .onTablesUpgraded(upgradedListner) // optional callback
                                .build();

Please note that adding DAO's dynamically (later) is not possible. You have to instantiate a DaoManager and pass all your DAO's in the constructor as seen above.

To sum up:

  • A DaoManager is representing the whole database file and basically is a SQLiteOpenHelper and manages SqlBrite instance for you.
  • A Dao is representing a table of a database. You define a public API for other software components of your App like getCustomers() or addCustomer() to query and manipulate the data of the underlying table.

License

Copyright 2015 Hannes Dorfmann

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

mosby

A Model-View-Presenter / Model-View-Intent library for modern Android apps
Java
5,489
star
2

AdapterDelegates

"Favor composition over inheritance" for RecyclerView Adapters
Java
2,934
star
3

fragmentargs

Annotation Processor for setting arguments in android fragments
Java
1,077
star
4

SwipeBack

SwipeBack for Android Activities to do pretty the same as the android "back-button" will do, but in a really intuitive way by using a swipe gesture
Java
695
star
5

annotationprocessing101

Java
431
star
6

ParcelablePlease

Annotation Processor for generating Parcelable code
Java
259
star
7

AnnotatedAdapter

Write less code with AnnotatedAdapter, an annotation processor for generating RecyclerView and AbsListView adapters
Java
195
star
8

debugoverlay

A tiny window overlay to log app internal on top of your android app
Java
151
star
9

mosby-conductor

Plugin for conductor to integrate Mosby
Java
131
star
10

CoordinatorsAndroid

Sample that shows how to apply the Coordinator Pattern on Android
Kotlin
121
star
11

Model-View-Intent-Android

A demo that shows how to apply Model-View-Intent on Android
Kotlin
86
star
12

AdapterCommands

Drop in solution to animate RecyclerView's dataset changes by using command pattern
Java
74
star
13

Instantiator

Tired of manually setup test data of Kotlin data classes or POJOs? Instantiator creates Instances of any class for you so that you can focus on writing tests instead of spending time and effort to setup test data
Kotlin
60
star
14

Vaadin-MVP-Lite

This is a Vaadin Addon that provides a Model-View-Presenter Framework
Java
51
star
15

CircleProgressView

Fork from SmoothProgressbar for internal development of another UI library ...
Java
38
star
16

mvi-timing

Just a simple demo app for blog post about MVI and Timing
Java
29
star
17

Todo-Testing-By-Design

Kotlin
13
star
18

rxworkshop

Kotlin
12
star
19

conductor-shared-element-transition

Kotlin
9
star
20

Vaadin-MVP-Lite-MailExample

This is an example project that shows how to use the VaadinMVP framework
JavaScript
9
star
21

appkit

Develop android application in a modern way. Write less code: appkit uses many popular Annotation Processing libraries like Butterknife, IcePick, Dependency Injection with Dagger and achieve a very clean software architecture with Model-View-Presenter (MVP)
Java
9
star
22

SecureBitcoinWallet

Java
8
star
23

SealedSubclassInstantiator

Instantiates instances of subclasses of a sealed class (Kotlin)
Kotlin
8
star
24

website-old

Personal blog, please read README
CSS
7
star
25

MosbyDagger

Example that shows best practices for Dagger2 + Mosby
4
star
26

AndroidCollections

Some usefu collection implementation like List, Map, Set (and combinations of all) etc. that can be useful in Android Projects
Java
4
star
27

OkHttpCertificate

Kotlin
3
star
28

hdlib

Java
2
star
29

fragmentargs-samples

Java
2
star
30

AndroidDesignPatterns

A Collection of Software Design Patterns for Android Applications
Java
2
star
31

ColorProgressBar

A circular (loading spinner) ProgressBar for Android that let you customize the colors of the loading spinner
Java
2
star
32

MosbyViewPagerDemo

Demo of viewpager + mosby
Java
1
star
33

RobolectircTest

Java
1
star
34

DexUtil

How many mehtods are used in your androids .dex file?
Java
1
star
35

annotationprocessing

Some utilities for writing annotation processors
Java
1
star
36

AndroidCollectionsTest

The eclipcse Android Test Project to run unit tests from eclipse
1
star
37

ason

Java
1
star
38

Vaadin-LoadingPanel

A simple LoadingPanel component, where you can switch beetween showing a loading animation and the "normal" content
Java
1
star
39

HippoHappa

Java
1
star
40

stdlib-android-test

Units test for the stdlib-android library
Java
1
star