EclipseでDatabaseConfigUtilを実行する方法

「実行の構成」の「DatabaseConfigUtil」のところで
JREタブを選択。未選択になっているのを「代替JRE」等、通常のJavaRuntimeを選択する。
「クラスパス」のところの「ブートストラップ・エントリー」からAndroidを除去し、「ユーザー・エントリー」にandroid.jarを追加する


DatabaseConfigUtilでテスト用のDTOもormlite_config.txt
に設定されてしまうため、実行後に消しておく
除外しないとreleaseパッケージでテストコードが除外されているためエラーになる

Android Ormlite Tutorial
Overview

This post entails step by step instructions on setting up OrmLite for an Android app using Android Studio. Also, the entire source code for this tutorial can be found on my Github account.

Objectives

This post covers an example Todo App using OrmLite in an Android project. Also, note that most of the code explanation is done via the comments in the following code snippets.

What is Ormlite?

It is an object relational mapping framework, which provides a set of simple lightweight functionalities to persist java objects to SQL databases, while alleviating the developer of the complexity and overhead of writing complex SQL queries.

Full Example

Adding ORMlite to the Android Studio project

image

Adding the Ormlite dependencies to the project

  1. Open the gradle file located in the root of the app folder.
  2. Add the following dependencies
    1. ‘com.j256.ormlite:ormlite-core:4.48′
    2. ‘com.j256.ormlite:ormlite-android:4.48′
  3. Sync gradle, and then the jar libraries will show up under the External Libraries section of the project.

Creating a sample Todo database model

https://gist.github.com/c85a9414dc787aa5c337

Take note of the  @DatabaseField annotation, this is what OrmLite uses to map the models to the sqlite database.

Creating the OrmliteOpenHelper class

The OrmliteOpenHelper class is used to manage the interaction between the java objects and the database, for e.g. it gives us a reference to the data access object (Dao).

https://gist.github.com/98cab03f4a1a6ff60cb6

The java Util program used to create database configuration script

Note: This program should be run as a standalone java application, not as an android application.

https://gist.github.com/3783a1e4811b6a31c63a

The configuration script created by the above Util program

https://gist.github.com/a370746845158f179574

Testing out Ormlite In an Android activity

https://gist.github.com/eafda691dd6be334bf92

The tutorial is done! Reach out to me if you have any questions or feedback.

Simplifying Android development with ORMLite

So you’re building an Android application that needs to store and manipulate persistent local data? On Android, there are only a few mechanisms available for persistent storage. Simple key/value storage is handled using SharedPreferences, basic filesystem access is available for flat files, and finally, SQLite is there for your serious data storage needs.

SQLite is a fantastic little database engine, as you probably know. Despite its simple-sounding name, it has a robust feature set, good performance, and is extremely stable (it’s possibly the most rigorously tested OSS project I’ve seen). I’ll assume for the moment that if you’re a software engineer in 2011, you are comfortable with relational databases and have a good understanding of the value of ORM (Object Relational Mapping). If not, it’s worth it to familiarize yourself with the concept on Wikipedia.

Enter ORMLite

ORMLite is an ORM for SQLite (I guess that was obvious from the name). Originally, it was developed using the JDBC drivers to talk to SQLite, not specifically for Android. The Android SDK makes available the java.sql.* classes, but they are undocumented and unsupported. Intead, Android makes available the proprietary android.database.sqlite.* API, which is basically your only way to do database storage.

Fortunately for us, in September 2010, Kevin Galligan took the initiative to add Android support to ORMLite, using the Android-specific database APIs. As a result, Android developers everywhere can use this great little ORM in their applications!

Getting Started with ORMLite

Pulling ORMLite into your project is simple: go to the Sourceforge files area and grab the latest ormlite-android package (4.14 at the time of this post). You only need the ormlite-android-4.14.jar, not the ormlite-core or any other packages. Drop the jar file into your project’s libs/ subdirectory and you’re ready to start.

ORMLite takes advantage of Java’s reflection API, combined with annotations, to make it very easy to use. Here’s an example of an object that can be written and read to the database via ORMLite:

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "people")
public class Person {

    // Constructor and other Person methods...

    @DatabaseField(columnName = "id", id = true, generatedId = true)
    private int m_id;

    @DatabaseField(columnName = "first_name")
    private String m_firstName;

    @DatabaseField(columnName = "last_name")
    private String m_lastName;

    @DatabaseField(columnName = "organization_id", canBeNull = false)
    private Organization m_organization;
}

In this stripped down example, there are a few things to notice. First: This is great! Just annotate my class as a table and its members as fields and we’re most of the way there!

The second thing to notice is that ORMLite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).

Finally, note that the last field, m_organization, is a reference to another object in the application. ORMLite recognizes this as a foreign key reference, and that the column actually refers to an id in another table. When you read a Person from the ORM, m_organization will refer to an Organization instance with only its id field populated. You can populate the rest of the fields by calling refresh() on the organization DAO.

Interacting with the database is done through a DAO (Data Access Object) which exposes operations like create, update, delete, and more general purpose objects like QueryBuilder. Here’s an example of creating a DAO and using it to create a Person in the database:

import java.sql.SQLException;
import com.j256.ormlite.android.AndroidConnectionSource;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.support.ConnectionSource;

...

public void createPerson(Person person) {
    ConnectionSource source = new AndroidConnectionSource(m_helper);
    try {
        DAO personDao =
                BaseDaoImpl.createDao(source, Person.class);
        personDao.create(person);
    } catch (SQLException e) {
        // Handle exception
    }
}

It doesn’t get much simpler. Note that ORMLite uses the helper object that you get from your SQLite database object to actually interact with the database.

Further Resources

Hopefully this is enough to whet your appetite and get you started. I plan to write some more posts about this topic, giving more in-depth examples and covering cases that aren’t as simple.

For more information on using ORMLite with Android, check out these pages:

OrmLite for Android

We have a project coming out soon.  Its the biggest one we’ve worked on, complexity-wise, anyway.  Its an iphone conversion, which made pretty heavy use of core data.  My (Kevin) original Android work was done before there was a phone, and I haven’t really done much on the platform after the G1 came out, so I assumed there would be some form of ORM tool available by now.  Well, when I looked around, there really wasn’t.  This is odd.  The Java community is huge, and there are plenty of ORM tools out there.  Why none for Android?

The first issue is performance.  Imagine using Hibernate on a phone.  Hibernate gets a lot of grief, but I use it for server code, and its a great tool.  Usually when people complain about performance its because they do stupid things.  But that’s on a server or desktop.  On a phone, any full-blown ORM is going to do a lot of extra garbage that you don’t need on a phone.  So, even if you could use one, you wouldn’t want to.  Any ORM tool for the phone has to be really basic.

No JDBC (even though there is).  Every tool that talks to a database in java uses JDBC, but Android doesn’t include a driver for the native Sqlite database, so you’d have to include your own (2+ megs), or use a different database (thanks.  Prefer not to explain to employer why I took a huge risk on their product).

Read More

Text
Photo
Quote
Link
Chat
Audio
Video