ORMDroid is a simple ORM persistence framework for your Android applications.

Related tags

O/R Mapping ormdroid
Overview

ORMDroid is a simple ORM persistence framework for your Android applications, providing an easy to use, almost-zero-config way to handle model persistence without ever having to deal with Android's built-in database interfaces.

ORMDroid is:

  • Small - ~20k, target of no more than 30k.
  • Simple - No excessive features or support for platforms other than Android.
  • Flexible - Allowing you to configure what you need to, but at the same time...
  • Automatic - ... sensible defaults for everything.

ORMDroid works with Android API 8 and up.

ORMDroid is available under the Apache license 2.0. Copyright (c)2012-2013 Ross Bamford & Contributors.

Getting ORMDroid

You can either download ORMDroid from the download page, or check out of Git.

If downloading a packaged release, you'll need to unzip the file somewhere, and then import the project into your Eclipse.

Getting started

To use ORMDroid, you need to set up ORMDroid as a required library in your android app. If you're using Eclipse, go to project->properties->android and add ORMDroid as a required libray. Now, you just need to add a single XML tag to your AndroidManifest.xml as a child of the Application tag:

<meta-data
  android:name="ormdroid.database.name"
  android:value="your_database_name" />

<meta-data
  android:name="ormdroid.database.visibility"
  android:value="PRIVATE||WORLD_READABLE||WORLD_WRITEABLE" />

And initialize the framework somewhere (e.g. Application.onCreate, or even in your activity's onCreate since there's no penalty for calling initialize multiple times):

ORMDroidApplication.initialize(someContext);

Then you create your model:

public class Person extends Entity {
  public int id;
  public String name;
  public String telephone;
}

And work with it as you see fit!

Person p = Entity.query(Person.class).where("id=1").execute();
p.telephone = "555-1234";
p.save();

There is also an object-oriented query API:

import static com.roscopeco.ormdroid.Query.eql;

// ... later

Person person = Entity.query(Person.class).where(eql("id", id)).execute();
p.telephone = "555-1234";
p.save();

That's it! If you want more customization over e.g. table names, column names, etc, take a look at the Table and Column annotations.

There is a more detailed version of these instructions in this blog entry

Update: There is now a very simple sample app available for ORMDroid. You can get it from Git:

git clone https://github.com/roscopeco/ormdroid-example.git

For more information, check out this blog entry.

Get in touch!

If you have questions, suggestions or just want to talk (about ORMDroid), get in touch via the Google Group.

Comments
  • One-to-many support.

    One-to-many support.

    There are a few changes here.

    • Bidirectional relationships are handled internally, so the user doesn't have to mark one an inverse anymore or pay attention to that (this was causing lots of problems with one-to-many.) This is done by temporarily caching just the prior Entities that could induce the circular reference. In order to support this, the Primary Key is the first field to be filled when an Entity is loaded.
    • One-to-many support. This adds a List TypeMapping, however the only supported list is currently an Entity list.
    • Simple order by in DESC.
    • Close leaked cursor.

    There are a few white-space removals, I apologize for that. My editor auto trims.

    opened by Queatz 6
  • Failed to open database exception, yet the database works

    Failed to open database exception, yet the database works

    On my HTC One I get "Failed to open database" exception all the time. Yet it seems that everything is working fine. How can I get rid of the exception?

    opened by xyxz-web 5
  • One to Many Relation

    One to Many Relation

    I thought ORMDroid can handle one to many relations as :

    public class MyObjet extends Entity
    {
        // ...
        private ArrayList<MyOtherObject> otherObjects;
    }
    
    public class MyOtherObject extends Entity
    {
        // ...
    }
    

    but not :

    com.roscopeco.ormdroid.TypeMappingException: Model MyObjet has unmappable field: public java.util.ArrayList otherObjects
    
    enhancement 
    opened by ChristopheCVB 4
  • Schema Upgrades when Entity Changes

    Schema Upgrades when Entity Changes

    Ross,

    My team is testing ORMdroid for use in our project. So far we like what we see.

    However, we have encountered an issue when adding fields to an existing Entity. As you probably already know, ORMdroid will throw an Exception when it encounters a field name that does not correspond to the underlying database table.

    Ideally, there would be a feature to automatically (or on demand) add new fields to the underlying table as the Entity object expands. I could imagine calling something after initializing the ORMDroidApplication in a new version of the app.

    Is there a means of triggering this sort of update in the existing ORMdroid library? If not, my team would be interesting in forking and contributing such a feature...based on any advice you may have.

    Thanks, Scott

    opened by shammer64 4
  • An ambigous exception on unknown type serialization

    An ambigous exception on unknown type serialization

    If there is a Java.util.date property on the entity, "Failed to instantiate model class - does it have a public null constructor?" exception is thrown.

    In this case it happened because Entity.load() method swallowed IllegalArgumentExeption and replaced it with ORMDroidException.

    catch (Exception e) { throw new ORMDroidException( "Failed to instantiate model class - does it have a public null constructor?", e); }

    Perhaps ORMDroidException should at least print e.getClass() for the original exception?

    But even then IllegalArgumentExeption does not quite indicate that there was a problem with type serialization. Needs better handling?

    On the subject of dates, since util.Date, maybe it is worth serializing it (maybe not)? Azure Mobile Services handles it this way and it works quite well:

    https://github.com/WindowsAzure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/com/microsoft/windowsazure/mobileservices/DateSerializer.java

    opened by rothschild86 3
  • I have fixed two issues that i have come across while using ormdroid

    I have fixed two issues that i have come across while using ormdroid

    Issue 1: When I have only one field except a dummy id field in my Entity extended class, query used to have a tailing comma.

    Fix File Entity.java

    +    private String stripTrailingComma(String string) {
    +      // check for last comma
    +      if (string.endsWith(",")) {
    +        return string.substring(0, string.length() - 1);
    +      }
    +      return string;
    +    }
    +
    +    int insert(SQLiteDatabase db, Entity o) {
    -      String sql = "INSERT INTO " + mTableName + " (" +getColNames()
    -          + ") VALUES (" + getFieldValues(db, o)+ ")";
    +      String sql = "INSERT INTO " + mTableName + " (" + stripTrailingComma(getColNames())
    +          + ") VALUES (" + stripTrailingComma(getFieldValues(db, o))+ ")";
    

    Issue 2: Cursor not closed while executing multiexecute query

    Fix File Entity.java

            /*
             * Moves cursor to start, and runs through all records.
             */
            <T extends Entity> List<T> loadAll(SQLiteDatabase db, Cursor c) {
                ArrayList<T> list = new ArrayList<T>();
    
                if (c.moveToFirst()) {
                    do {
                        list.add(this.<T> load(db, c));
                    } while (c.moveToNext());
                }
    +                       c.close();
    
                return list;
            }
    
    bug 
    opened by akshaydeo 3
  • Problem with the Sample (where function)

    Problem with the Sample (where function)

    I have downloaded the sample from http://orm-droid.googlecode.com/svn/trunk/ORMSample I am getting and error with the following method in Person class.

    public List people() { return query(Person.class).where("department").eq(id).executeMulti(); }

    The argument for where is invalid because its expecting type com.roscopeco.ormdroid.SQLExpression while the passed argument is String.

    Same error is present in the activity classes,when calling the where method

    Please advise me how to fix this

    question 
    opened by kmajeed 3
  • Security Exception

    Security Exception

    I'm getting the following exception, although I'm not sure if ormdroid's causing it. All I know is that I'm referencing Entitys in my code when it happens.

    12-17 17:48:57.155     847-1466/? E/DatabaseUtils﹕ Writing exception to parcel
        java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
                at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:13090)
                at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2038)
                at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:607)
                at android.content.ContentProvider$Transport.call(ContentProvider.java:279)
                at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273)
                at android.os.Binder.execTransact(Binder.java:388)
                at dalvik.system.NativeStart.run(Native Method)
    
    opened by Queatz 2
  • Man extends Person

    Man extends Person

    To test your library, I made a simple test : I created a class Man extends Person extends Entity. When I try to load all Person in DB, only the Person table is loaded. I was expecting that Man table would also be returned.

    Entity.query(Person.class).executeMulti();
    

    Am I doing something wrong ?

    Not sure if it is a bug, but an enhancement :D

    From that, awesome job guys !

    enhancement question 
    opened by ChristopheCVB 2
  • ORMDroid attempts to map public static final vars

    ORMDroid attempts to map public static final vars

    android frequently uses int/string constants instead of enum's.. .attempting any setting of these causes expected errors.

    ex

    public class User{ public final static int USER_TYPE_ADMIN = 0; public final static int USER_TYPE_SUPERADMIN=1;

    public int userType;

    }

    I had to move the constants out into another class, then deserializing from db worked properly again.

    Perhaps we should ignore, or if we can access protection levels and whether or not its static / non-static, we should automatically ignore said fields? (we'll never be able to set a static var like the actual USER_TYPE_ADMIN in this case).

    Otherwise we could put together an ignore annotation for explicit ignoring.

    bug 
    opened by ronnyek 2
  • mTransient is not set to true on delete()

    mTransient is not set to true on delete()

    I noticed, that mTransient is not reset to true, if I call delete() on an Entity from database. I'm not sure if this has any deeper reason, but I think this may cause some unexpected behavior - at least it did for me.

    opened by j-be 1
  • Modify the path of the database

    Modify the path of the database

    good morning how are you

    I have tried the library, and it works fine, but I want to change the path of the database, there is some way to do it, excellent work, thanks

    opened by powellbird 1
  • Cursor problems.

    Cursor problems.

    Exception Fatal Exception: java.lang.RuntimeException Unable to start activity ComponentInfo{ }: java.lang.IllegalStateException: Couldn't read row 0, col 18 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

    Problem is caused where executeMulti, is an random errror.

    opened by saulomano 0
  • Database Upgrade/Migration

    Database Upgrade/Migration

    Are you thinking about implementing a way to be able to upgrade/migrate the database ?

    I see 2 ways :

    • Adding Version in Manifest and a script in assets to allow manual migration
    • Adding Version in Manifest and checking Tables programmatically at the app init

    Of course, there are other ways to do that. What are your thoughts about it @roscopeco ?

    opened by ChristopheCVB 2
  • Entity id and save

    Entity id and save

    What if I want to use the same ids used in my server ? I create a Entity instance specifying my own id, then I save it, ORMDroid throws away my own id and replaces it by last_insert_rowid. I'm stuck there. I think I have to create a new field, like cloudId, and use this one when manipulating Entities... Is there any other work around ?

    Thanks !

    opened by ChristopheCVB 2
Releases(v0.40)
  • v0.40(Aug 12, 2013)

    ORMDroid 0.40

    This is the first packaged release of ORMDroid since 0.20, and introduces the following major features:

    • New Query API - The new Query API provides a programmatic way of building queries, and shields you from SQL while still allowing you to use string queries if you wish.
    • DateMapper - A community-supplied mapping for java.util.Date objects.
    • No default mapping - The default mapping has been removed. If your code relied on it, you should change it now.
    • Bugfixes galore - Thanks to community feedback and pull requests, some nasty bugs have been squashed.

    This release marks the last call for feature requests before 1.0. The next release will be 0.50, which will essentially be the start of testing for the 1.0 cycle.

    Check out the changelogs on Github for full details.

    Source code(tar.gz)
    Source code(zip)
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
requery - modern SQL based query & persistence for Java / Kotlin / Android

A light but powerful object mapping and SQL generator for Java/Kotlin/Android with RxJava and Java 8 support. Easily map to or create databases, perfo

requery 3.1k Dec 29, 2022
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
A Java/Kotlin library for Android platform, to manage bean's persistence in SQLite, SharedPreferences, JSON, XML, Properties, Yaml, CBOR.

Thanks to JetBrains for support Kripton Persistence Library project! Kripton Persistence Library Kripton is a java library, for Android platform, that

xcesco 117 Nov 11, 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
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
Compile-time active record ORM for Android

Ollie Compile-time active record ORM for Android. Multiple mapping methods. SQLiteDatabase-like interface (QueryUtils.java). Lightweight query builder

Michael Pardo 423 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
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
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
Sprinkles is a boiler-plate-reduction-library for dealing with databases in android applications

Sprinkles Sprinkles is a boiler-plate-reduction-library for dealing with databases in android applications. Some would call it a kind of ORM but I don

Emil Sjölander 781 Nov 28, 2022
Upsert DSL extension for Exposed, Kotlin SQL framework

Exposed Upsert Upsert DSL extension for Exposed, Kotlin SQL framework. Project bases on various solutions provided by community in the official "Expos

Dzikoysk 23 Oct 6, 2022
Upsert DSL extension for Exposed, Kotlin SQL framework

Exposed Upsert Upsert DSL extension for Exposed, Kotlin SQL framework. Project bases on various solutions provided by community in the official "Expos

Reposilite Playground 23 Oct 6, 2022