Compile-time active record ORM for Android

Related tags

O/R Mapping Ollie
Overview

Ollie

Build Status Stories in Ready

Compile-time active record ORM for Android.

Usage

Define model

@Table("notes")
class Note extends Model {
	@Column("title")
	public String title;
	@Column("body")
	public String body;
}

Initialize

Ollie.with(context)
	.setName(DB_NAME)
	.setVersion(DB_VERSION)
	.setLogLevel(LogLevel.FULL)
	.setCacheSize(CACHE_SIZE)
	.init();

Update database

Note note = new Note();
note.title = "My note";
note.body = "This is my note.";
note.save();

Query database

// Get all notes
List<Note> notes = Select.from(Note.class).fetch();

// Get a single note
Note note = Select.from(Note.class).fetchSingle();

// Get notes table count
Integer count = Select.columns("COUNT(*)").from(Note.class).fetchValue(Integer.class);

// Get observable of all notes
Select.from(Note.class).observable()
	.subscribe(notes -> {
		// do stuff with notes
	});

// Get observable of a single note
Select.from(Note.class).observableSingle()
	.subscribe(note -> {
		// do stuff with note
	});
	
// Get observable of notes table count
Select.columns("COUNT(*)").from(Note.class).observableValue(Integer.class)
	.subscribe(count -> {
		// do stuff with count
	});

Download

Grab via Maven:

<dependency>
  <groupId>com.michaelpardo</groupId>
  <artifactId>ollie</artifactId>
  <version>0.3.1</version>
</dependency>
<dependency>
  <groupId>com.michaelpardo</groupId>
  <artifactId>ollie-compiler</artifactId>
  <version>0.3.1</version>
  <optional>true</optional>
</dependency>

or Gradle:

compile 'com.michaelpardo:ollie:0.3.1'
provided 'com.michaelpardo:ollie-compiler:0.3.1'

Latest snapshot: 0.3.2-SNAPSHOT

Build

To build:

$ git clone [email protected]:pardom/ollie.git
$ cd ollie/
$ ./gradlew build

License

Copyright 2014 Michael Pardo

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.
Comments
  • Delete all data in one table

    Delete all data in one table

    How can I delete all the data in one table?

    new Delete().from(Car.class).execute(); Gives me a "java.lang.IllegalArgumentException: Empty bindArgs".

    EDIT: With "new Delete().from(Car.class);" I don't get an error - but nothing isn't deleted.

    opened by Rainer-Lang 25
  • ClassNotFoundException: ollie.AdapterHolderImpl

    ClassNotFoundException: ollie.AdapterHolderImpl

    Hi, so I have just integrated Ollie in my newest app and it is giving me strange errors. It compiles without any errors, but crashes right on startup.

    Here's the stacktrace: https://gist.github.com/anonymous/a8d3fcb2fb4cd92a2dc4

    I believe I've added it using Gradle the right away:

    compile 'com.michaelpardo:ollie:0.3.1'
    provided 'com.michaelpardo:ollie-compiler:0.3.1'
    

    Here's the model:

    @Table(SavedDefinitions.TABLE_NAME)
    public class SavedDefinitionEntry extends Model {
    
        // Data
        @Column(SavedDefinitions.KEY_WORD)              public String mWord;
        @Column(SavedDefinitions.KEY_PHONETIC_TEXT)     public String mPhoneticText;
    
        public SavedDefinitionEntry(String mWord, String mPhoneticText) {
            this.mWord = mWord;
            this.mPhoneticText = mPhoneticText;
        }
    
    }
    

    I am having a hard time solving this error. Any ideas? :(

    opened by saket 14
  • model error

    model error

    when I define a model, and then run the app, it has errors. Error:Execution failed for task ':app:compileDebugJava'.

    java.lang.NoClassDefFoundError: android/content/ContentValues

    i Use api 21.

    opened by jiqimaogou 14
  • db field has null-value

    db field has null-value

    I have an integer column with null-values inside. I store dates in this col. If I load the ollie-object I always get dates with 0 -> 01.01.1970 How can I get the null value (stored in the database) back?

    If I load the value from db with fetchValue(String.class) I get the null value...

    opened by Rainer-Lang 9
  • NullPointerError when loading an entity that contains references to another entity

    NullPointerError when loading an entity that contains references to another entity

    First off, I'm totally looking forward to continuing to play around with ollie. I stumbled across this issue while testing our ollie in my application. I had a entity lets call it "notebook" which contained a "note". I could successfully create the notebook and see it in my notebook list view and the database looked correct. But once I killed the app and reopened it I would get NPE in my notebook list view because the note was null (even though an tag id was successfully populated in the database)

    I traced it back to the ModelAdapter which was attempting to load the Note using the field on the entity. The note field on the entity was null because the entity was being loaded fresh from the database.

    Here is the generated source file:

    public final class Notebook$$ModelAdapter extends ModelAdapter<Notebook> {
                public final Class<? extends Model> getModelType() {
                    return Notebook.class;
                }
    
                public final String getTableName() {
                    return "notebooks";
                }
    
                public final String getSchema() {
                    return "CREATE TABLE IF NOT EXISTS notebooks (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, note INTEGER)";
                }
    
                public final void load(Notebook entity, Cursor cursor) {
                    entity.id = cursor.getLong(cursor.getColumnIndex("_id"));
                    entity.name = cursor.getString(cursor.getColumnIndex("name"));
                    entity.note = Ollie.getOrFindEntity(entity.note.getClass(), cursor.getLong(cursor.getColumnIndex("note")));  // This is the NPE
                }
    
                public final Long save(Notebook entity, SQLiteDatabase db) {
                    ContentValues values = new ContentValues();
                    values.put("_id", entity.id);
                    values.put("name", entity.name);
                    values.put("note", entity.note != null ? entity.note.id : null);
                    return insertOrUpdate(entity, db, values);
                }
    
                public final void delete(Notebook entity, SQLiteDatabase db) {
                    db.delete("notebooks", "_id=?", new String[]{entity.id.toString()});
                }
    }
    
    opened by wontondon 7
  • Expected behavior on deleted entities

    Expected behavior on deleted entities

    I want to make sure that this assertion is what people expect when an entity is deleted:

    Note note = new Note();
    note.body = "this is draft";
    note.save();
    Delete.from(Note.class).execute();
    
    assertThat(note.id).isNull();
    

    There are several operations we might expect (or not) when an entity is deleted. These operations could be supported by overloading Delete.execute() with booleans.

    • Set entity id to null.
    • Set entity to null.
    • Remove entity from cache.

    I think it's reasonable to set id to null because it no long exists in the database, however I can think of scenarios where there is use for it.

    I don't think it's reasonable (as a default) to set the entity to null. If there are entities used elsewhere in the app, they will then be null.

    Removing entities from the cache seems reasonable, since there is no scenario where they will be retrieved from it. However, it won't hurt to leave them in there since they will be evicted naturally from lack of use (LRU cache). The only issue with this is that the cache will eventually grow to its max size.

    My preference is to only set id to null and provide an override of Delete.execute() whereby passing in false will not set the id to null.

    Thoughts?

    question 
    opened by pardom-zz 6
  • Compilation fails with an NullPointerException

    Compilation fails with an NullPointerException

    Hello. Before anything else, thanks for creating Ollie. Now, I cannot understand why, but I'm unable to build my project with this library. The only error I'm seeing is:

    Error:Execution failed for task ':SMSX:compileDebugJava'.
    > java.lang.NullPointerException
    

    That's it. Nothing else. Model class: https://gist.github.com/anonymous/3c3cb0465b8ecdd2ee57

    I'm initializing Ollie inside my Application class. Any idea how to fix this? Thank you.

    Update: So replacing the primitives in my model class with their Wrapper classes fixed the issue. Am I doing this right?

    opened by saket 5
  • Fix Issue #18

    Fix Issue #18

    I opened up https://github.com/pardom/ollie/issues/18. I have created a fix for the issue and created some unit tests. I'm not sure if this is the expected behavior, but it seems to be working for me. Hopefully, it helps.

    opened by wontondon 5
  • it has no way to insert entity with id.

    it has no way to insert entity with id.

    if I have an entity with id value, when I call save, it could not be inserted into the database. can you provide model.replace() method?

    when the contentprovider is supported, everytime I save the entity, it will call notifychange(), sometimes, I want to insert a list of entities into the database, it will call notifychange() many times, can you provide some funtion to prevent notifychange().

    opened by jiqimaogou 4
  • NPE

    NPE

    I'm getting a NPE and I don't know why. :-(

    :app:compileDebugJava FAILED

    Caused by: java.lang.NullPointerException at ollie.internal.codegen.Registry.getTypeAdapterElement(Registry.java:83) at ollie.internal.codegen.element.ColumnElement.(ColumnElement.java:73) at ollie.internal.codegen.step.ModelAdapterStep.addColumnElements(ModelAdapterStep.java:89) at ollie.internal.codegen.step.ModelAdapterStep.process(ModelAdapterStep.java:65)
    at ollie.internal.codegen.OllieProcessor.process(OllieProcessor.java:76) at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:793) at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:722) at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1700(JavacProcessingEnvironment.java:97) at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1029) at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1163) at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1108) at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:824) at com.sun.tools.javac.main.Main.compile(Main.java:439) ... 65 more

    BUILD FAILED

    opened by Rainer-Lang 4
  • Adding ability to use getters and setters as opposed to public methods.

    Adding ability to use getters and setters as opposed to public methods.

    Great work on this library. I was always a fan of the syntax in https://github.com/pardom/ActiveAndroid, but the performance hit against reflection on annotations seemed like a downside so I was really happy to see Ollie pop up.

    One of the things I didn't particularly like when integrating with my existing model schema was that all the fields had to be public, so I added a new annotation called @GetSet that tells the generated classes to look for getter and setter methods instead of accessing the fields directly.

    opened by iainconnor 4
  • Ollie Deprecated

    Ollie Deprecated

    Hello community,

    Ollie is now deprecated. I'm grateful for everyone's contributions and support over the years, however I believe that there are many better alternatives. Ollie was an attempt to make a better ActiveAndroid alternative, and that library is also deprecated as of today.

    The reason this notice is coming to you via GitHub issue rather than the README is because I no longer have access to this GitHub account. Now that this account has been dormant for six months, I have reclaimed my username, but still do not have contributor access. I don't know how long the dormant account will remain visible, so I suggest forking the library if you wish to continue work on it.

    I strongly endorse Square's excellent SQLDelight as an alternative to this library.

    Thanks again,

    Michael Pardo

    opened by pardom 0
  • Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > java.lang.NullPointerException

    Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > java.lang.NullPointerException

    apply plugin: 'com.android.application'

    android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.leavingstone.aversi" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" }

    dataBinding {
        enabled = true
    }
    
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        disable 'InvalidPackage'
    }
    

    } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile files('libs/core-3.2.1-sources.jar') compile files('libs/core-3.2.1.jar') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.0' compile 'com.android.support:design:23.2.0' compile 'com.specyci:residemenu:1.6+' compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28' compile 'com.google.code.gson:gson:2.5' compile 'com.android.support:percent:23.2.0' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.google.android.gms:play-services:8.4.0' compile 'com.michaelpardo:ollie:0.3.1' provided 'com.michaelpardo:ollie-compiler:0.3.1'

    } apply plugin: 'com.google.gms.google-services'

    opened by developer-- 3
  • Trouble upgrading database

    Trouble upgrading database

    I'm seeing some strange behavior. I added a field to a class and incremented the DB version number so I should have the new column but I'm seeing:

    E/Ollie﹕ Failed to process cursor.
        java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
    

    And a no such column SQLLite exception:

    E/LoginFragment﹕ Encountered a problem with login.
        android.database.sqlite.SQLiteException: no such column: profile_image_id (code 1): , while compiling: UPDATE users SET apid=?,profile_image_id=?,password=?,external_id=?,last_name=?,email=?,authentication_token=?,_id=?,first_name=?,phone_number=? WHERE _id=?
    

    Any suggestions appreciated.

    opened by isuPatches 2
  • Concurrency issues

    Concurrency issues

    Hello, it seems that there are concurrency issues. I have an ollie model Task.java with 2 tables:

        @SerializedName(SERVER_ID)
        @Column(SERVER_ID)
        @Unique(ConflictClause.REPLACE)
        public String mServerId;
    
        @Column(NEW_CONTENT)
        public Boolean mHasNewContent;
    
        public synchronized void setServerId(String serverId) {
            mServerId = serverId;
            save();
        }
    
        public synchronized void setHasNewContent(Boolean accessed) {
            mHasNewContent = accessed;
            save();
        }
    

    If Thread A calls setServerId and Thread B calls setHasNewContent right after that, it can happen, that the mServerId is lost and back to null.

    Any ideas why and how this can happen? I don't seem to can synchronize this case outside of Ollie by myself.

    opened by markini 0
Releases(0.3.1)
Owner
Michael Pardo
Michael Pardo
Active record style SQLite persistence for Android

ActiveAndroid ActiveAndroid is an active record style ORM (object relational mapper). What does that mean exactly? Well, ActiveAndroid allows you to s

Michael Pardo 4.7k Dec 29, 2022
Compile time processed, annotation driven, no reflection SQLite database layer for Android

SqliteMagic Simple yet powerful SQLite database layer for Android that makes database handling feel like magic. Overview: Simple, intuitive & typesafe

Siim Kinks 118 Dec 22, 2022
RecordMe - Record your voice application with kotlin

RecordMe A simple voice recording app. Made Using : Kotlin, Navigation Component

Steve Waweru 2 Apr 28, 2022
A blazing fast, powerful, and very simple ORM android database library that writes database code for you.

README DBFlow is fast, efficient, and feature-rich Kotlin database library built on SQLite for Android. DBFlow utilizes annotation processing to gener

Andrew Grosner 4.9k Dec 30, 2022
greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.

Check out ObjectBox Check out our new mobile database ObjectBox (GitHub repo). ObjectBox is a superfast object-oriented database with strong relation

Markus Junginger 12.6k Jan 3, 2023
Android ORM

Shillelagh Shillelagh is an sqlite library. It was built to make life easier. The entire library was built around simplicity when using sqlite in Andr

Andrew Reitz 49 Sep 11, 2020
A blazing fast, powerful, and very simple ORM android database library that writes database code for you.

README DBFlow is fast, efficient, and feature-rich Kotlin database library built on SQLite for Android. DBFlow utilizes annotation processing to gener

Andrew Grosner 4.9k Dec 30, 2022
lightweight and minimalist ORM for Java/Android. works with SQLite & MySQL. (not actively maintained)

Description ORMAN is an minimalistic and lightweight ORM framework for Java which can handle your common database usage without writing SQL and strugg

Ahmet Alp Balkan 246 Nov 20, 2022
ORMDroid is a simple ORM persistence framework for your Android applications.

ORMDroid is a simple ORM persistence framework for your Android applications, providing an easy to use, almost-zero-config way to handle model persist

Ross Bamford 87 Nov 10, 2022
AndroidQuery is an Android ORM for SQLite and ContentProvider which focuses on easy of use and performances thanks to annotation processing and code generation

WARNING: now that Room is out, I no longer maintain that library. If you need a library to easy access to default android ContentProvider, I would may

Frédéric Julian 19 Dec 11, 2021
LiteOrm is a fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line of code efficiently.

#LiteOrm:Android高性能数据库框架 A fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line

马天宇 1.5k Nov 19, 2022
lightweight and minimalist ORM for Java/Android. works with SQLite & MySQL. (not actively maintained)

Description ORMAN is an minimalistic and lightweight ORM framework for Java which can handle your common database usage without writing SQL and strugg

Ahmet Alp Balkan 246 Nov 20, 2022
An ORM for Android with type-safety and painless smart migrations

Android Orma Orma is a ORM (Object-Relation Mapper) for Android SQLiteDatabase. Because it generates helper classes at compile time with annotation pr

The Maskarade project 440 Nov 25, 2022
Performance comparison of Android ORM Frameworks

Performance comparison of Android ORM Frameworks At the moment there are a lot of ORM-libraries for the Android OS. We reviewed the most popular ones

Alexey Zatsepin 328 Dec 21, 2022
a 3d database ORM experiment. (used in two commercial projects)

Android-TriOrm a 3d database ORM experiment for Android. (used in two commercial projects). based around small tables concept and JVM Serialization. H

Tomer Shalev 19 Nov 24, 2021
JAKO: Just Another Kotlin Orm (PostgreSQL)

JAKO: Just Another Kotlin Orm (PostgreSQL) JAKO is a simple, minimal, no-dependency library to build and execute postgresql statements using a fluent

Alessio 6 May 27, 2022
LiteGo is a Java-based asynchronous concurrency library. It has a smart executor, which can be freely set the maximum number of concurrent at same time , and the number of threads in waiting queue. It can also set waiting policies and overload strategies.

LiteGo:「迷你」的Android异步并发类库 LiteGo是一款基于Java语言的「异步并发类库」,它的核心是一枚「迷你」并发器,它可以自由地设置同一时段的最大「并发」数量,等待「排队」线程数量,还可以设置「排队策略」和「超载策略」。 LiteGo可以直接投入Runnable、Callable

马天宇 189 Nov 10, 2022
Object-relational mapping for Android

RushOrm Object-relational mapping for Android RushOrm replaces the need for SQL by mapping java classes to SQL tables. What is the aim? The aim is to

Stuart Campbell 172 Nov 11, 2022
Insanely easy way to work with Android Database.

Sugar ORM Insanely easy way to work with Android databases. Official documentation can be found here - Check some examples below. The example applicat

null 2.6k Dec 16, 2022