ORMLite Create Table

ORMLite is ORMappter for several platform.

In this blog, I’ll explain about Android ORMLite.

Nice thing to use ORMapper is easy to understand how to use DB.
User operates only Java class to manage database. No SQL query.

Download and Add build path

We need to download following 2 files from ORMLite.

  • ormlite-android-4.45.jar
  • ormlite-core-4.45.jar

In Android, Core and Android is required.

Code

  • Management class which exntends OrmLiteSqliteOpenHelper(create table, upgrade schema, add initial data)
  • Entity class represents table
  • DataAccessObject to manage data

First and second are fixed style.
DAO is next blog.

Manage class

public class ORMDatabaseHelper extends OrmLiteSqliteOpenHelper 
{
	private static final String DBFILE = "app.db";
	
	private static int VERSION = 1;
	
	public ORMDatabaseHelper( Context context )
	{
		super( context, DBFILE, null, VERSION );
	}
	
	
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource cs) 
	{
		// Add Table Creation
		try
		{
			TableUtils.createTable(cs, Setting.class);
		}
		catch ( SQLException oops)
		{
			oops.printStackTrace();
		}
		// Add First data insert
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource cs, int oldVersion,
			int newVersion) 
	{
		// Add upgrade operation

	}

}

This is similar style when creating general SQLite use in Android.
No SQL schema to create table.
TableUtils.createTable is creation part.
Setting.class is Entity class. Entity class is next.

Entity

@DatabaseTable(tableName = "setting" )
public class Setting 
{
	@DatabaseField(generatedId=true)	// For Autoincrement
	private Integer id;
	
	@DatabaseField
	private String key;
	
	@DatabaseField
	private Integer value;
}

Entity class represents table, column, and java class.
Use some annotation to indicate

Annotation Description
@DatabaseTable Table name etc..
@DatabaseField Column, field

This is simple class. There are id(autoincrement), string.

Test Activity

To create table, create ORMDatabaseHelper

public class MainActivity extends Activity 
{
    ORMDatabaseHelper dbHelper;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
		
	ORMDatabaseHelper dbhelper = new ORMDatabaseHelper(this);
    }
}

It is same behavior of Simple SQLite class to prepare in Android SDK.
If there are no database and table, create when call constructor.
When creating, DDMS shows schema of these tables.