My favorites | Sign in
Project Logo
                
Search
for
Updated May 31, 2007 by amedlock
API  
Usage API

Programming interface

Initialize the library

First you must import the classes for the library via:

import com.ormlite.*;

Next you must load your mapping files. You can load a file directly like this:

ORM.loadFile( "c:/myfile.xml" );

or if the mapping file is on your classpath you can do this:

ORM.loadResource("mappings/mymap.xml");

Next you must set up one or more data sources. They are referred to by name in the <data> mapping element(explained below). If one is not specified the default mapping is used which is named default.

You set them with the setDataSource method:

ds = new DataSource(...);
ORM.setDataSource( "mysource", ds );

You can set the default datasource like:

ORM.setDataSource(ds);

This is the datasource which will be used if one is not specified for a <data> mapping element.

Using Spring

If you are using spring a class called ORMConfig is supplied which will make setting up the ORM easy. The following methods are provided:

setDataSources( Map sources );
setMappingFiles( Properties files );
setResourceFiles( Properties files );

Here is a sample XML snippet showing how to use the class:

<!-- Example of configuring ORMLITE using Spring IOC framework -->
<beans>
  <bean id="myDataSource" class="com.foo.bar.DataSource">
    ...
  </bean>
  <bean id="dataSourceDeux" class="com.foo.baz.DataSource>
    ...
  </bean>

  <bean id="ormLoader" class="com.ormlite.ORMConfig">
    <property name="dataSources">
      <map>
        <prop key="default" ref="myDataSource" />
        <prop key="other" ref="dataSourceDeux" />
      </map>
    </property>

    <property name="mappingFiles">
      <values>
      mappingfileA.xml
      mappingfileB.xml
      </values>
    </property>

    <property name="resourceFiles">
      <values>
      classPathFile.xml
      </values>
    </property>
  </bean>
</beans>

Overall API Layout

There are static methods in the com.ormlite.ORM class which allow Create, Read, Update and Insert. These methods refer to <data> definitions by Java class or by name.

All queries against a datasource use the Query class, which also refers to <data> definitions by Java class or name.

The preferred method to write to the database is to use the BaseRecord class to extend your objects, which has the same functionality added via inheritance(mixin).

Reading records

Once data definitions are loaded, you can load all the records in a table via:

List items = ORM.findAll( "Datatype" );

or

List items = ORM.findAll( MyRecord.class );

If you wish to load specific items you create a Query object like this:

Query q = new Query( MyRecord.class ); // specify by class

Query q = new Query( "MyRecord" ); // specify by name

or using the ORM class:

Query q = ORM.find( "MyRecord");

This method is easier when chaining method calls(see below).

A Query object has a where method which allows conditions to be added to the query:

q.where("id = :myvar")

Note that a variable was used in the clause using a colon prefix. You should not use values directly in the where clauses to avoid SQL Injection vulnerability. Literals can also cause problems for ormlite when creating select clauses from multiple tables.

A note on column/field references

When you add conditions to your queries, you should refer to values by either:

  • TableName.ColumnName
  • DataDefinitionName.FieldName
  • FieldName

It is preferred you use one of the first two options, as the third option could cause confusion in some circumstances. (Not to mention the first two are much clearer)

So if you have a data definition like this:

<data name="Foo">
  <table name="Bar">
    <field type="string" name="baz" column="baz1" />
  </table>
</data>

You could use:

q.where("Foo.baz = :myvar")

or

q.where("Bar.baz1 = :myvar")

Variable values

A Query object contains a set of variable bindings. They can be set directly:

q.set( "myvar", new Integer(100) ); (new not needed with 1.5+ autoboxing)

you can also set the SQL type directly:

`q.set( "myvar", java.sql.Types.NUMERIC, 100 );

If you have a Map of bindings you can pass it in the where clause also:

Map myvars = new HashMap();
myvars.put( "myvar", new Integer(100) );
q.where("id= :myvar", myvars );

In Groovy its even easier:

q.where( "id = :myvar", [ 'myvar' : 100 ] )

Once the Query is configured, you can retrieve all records using the all method:

List items = q.all();

Or if you need a subset of records you can use the first and from methods:

List items = q.first( 100 );

List items = q.from( 100, 200 );

Or if you need just the first element:

Object item = q.first();

Note that the query object methods return itself so chaining calls makes for simple API calls:

Foo foo = (Foo)ORM.find("Foo").where("id = :myid", binds ).first();

Inserting records

Writing records are very easy. Create an object you wish to store, ensuring that all the key fields are set. Then call:

ORM.insert( object );

The data definition is found using the class of the passed object. If you have multiple data definitions using the same class the data definition cannot be found using the type alone. In this case you need to pass the name of the data definition:

ORM.insert( "MyRecord", object );

The only caveat is that primitive types(int,float..) will always be written, since they cannot be set to null. For this reason I suggest you use non-primitive types when possible.

Updating and Deleting records

Deleting or Updating records are also quite easy.

  1. Create or read an object you wish to update, changing fields as needed.
  2. Call ORM.update( object ); or ORM.delete( object );

Again the data definition is found using the class of the passed object and the key fields cannot be null.

Again, if you have multiple <data> definitions sharing the same class the name of the data definition name must be passed in:

ORM.delete( "MyRecord", object );

Extending BaseRecord

If you extend your Java Bean from class com.ormlite.BaseRecord, you get the following methods which will simplify updating the database.

  1. insert() this will insert a new record.
  2. update() this will update the record, primary key(s) must be set
  3. delete() this will delete the record, primary key(s) must be set

The restriction above still applies to the use of BaseRecord: The class must map to only one <data> definition. In this case if you wish to reuse a class, you must extend it with an empty class declaration:

class MyRecord extends BaseRecord { .... }
class MyRecordToo extends MyRecord {} // same class, different data definition

Loading child objects

If you have child objects specified in your XML file, you can load them using the following BaseRecord methods:

List   findChildren(Class cls);
List   findChildren(String name);

These two methods will find the child using the name or Java class and load any child objects using the keys specified in the XML.

public void loadAllChildren();

This method will load all children specified in the XML and store the results in the appropriate java class members. If the mapping is one to one, the set method must accept an appropriate java object. If the mapping is one to many, the method must accept a subclass of java.util.List.

int   deleteChildren(Class cls);
int   deleteChildren(String name);

These methods will delete the children using the <child> node in the XML which matches the name or class passed in. Both return the number of records deleted.


Sign in to add a comment
Hosted by Google Code