SQLBrite DAO


Source link: https://github.com/sockeqwe/sqlbrite-dao

SQLBrite DAO

Dependencies

Latest version:

// 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. 

Resources

EchantedViewPager is a custom ViewPager that provides some custom and usefull functionalities, such as, scalling scroll, alpha scroll and swipe to dismiss option.

SyncIt will call a method implemented in your activity to notify data connection changes.

Library to collapse inner objects when parsing json.

Diffre is a sample Android application that shows how to change text color based on background. Useful for event progress like views.

This library allows you to implement a pin lock mechanism in your app easily.

Once enabled a four-digit passcode needs to be entered any time your mobile app is launched. This way your app is safe even if your smartphone or tablet falls into the wrong hands.

A horizontal progressbar.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes