| sormula | simple (easy) object relational mapping | |
|
These examples use a default data source for all active record operations. A default data source is set with
ActiveDatabase#setDefault.
You may also have multiple data sources for record objects using
ActiveRecord#attach or
implicitly when using an ActiveTable
that is constructed with a specific data source. See org.sormula.active pacakge for the active record javadoc.
Sormula can use a data source directly or look it up with JNDI. Update one record using active record methods:
public void removeInventory(int partNumber, int delta)
{
// perform within transaction for the default active database
ActiveTransaction transaction = new ActiveTransaction();
try
{
transaction.begin();
// get part by primary key
Inventory inventory = Inventory.table.select(partNumber);
// update
inventory.setQuantity(inventory.getQuantity() - delta);
inventory.update();
transaction.commit();
}
catch (ActiveException e)
{
transaction.rollback();
e.printStackTrace();
}
}
Update a collection of records using active record methods:
public void clearInventory(String manufacturerId) throws Exception
{
// perform within transaction for an active database
ActiveTransaction transaction = new ActiveTransaction(new ActiveDatabase(dataSource));
try
{
transaction.begin();
// select for a specific manufacturer ("manf" is name of where annotation in Inventory.java)
List<Inventory> list = Inventory.table.selectAllWhere("manf", manufacturerId);
// for all inventory of manufacturer
for (Inventory inventory: list)
{
inventory.setQuantity(0);
}
// update
Inventory.table.updateAll(list);
transaction.commit();
}
catch (ActiveException e)
{
transaction.rollback();
e.printStackTrace();
}
}
Inventory DDL:
CREATE TABLE INVENTORY
(
PARTNUMBER INTEGER PRIMARY KEY,
QUANTITY INTEGER,
MANUFACTURERID VARCHAR(40)
)
Inventory.java:
@Wheres({
@Where(name="manf", fieldNames="manufacturerId") // where manf=?
})
public class Inventory extends ActiveRecord<Inventory>
{
private static final long serialVersionUID = 1L;
public static final ActiveTable<Inventory> table = table(Inventory.class);
int partNumber;
int quantity;
String manufacturerId;
getters/setters...
}
Identity columns are simple...
Identity Column Example |
|
| © 2011-2012 Jeff Miller |