Chapter 25. Code Engineering

  1. Home
  2. Docs
  3. Chapter 25. Code Engineering
  4. 5. Object Relational Mapping
  5. Using the generated ORM code

Using the generated ORM code

Download PDF

The following sections demonstrate how to use the generate ORM code with factory method persistent API.

Inserting records

  1. Create persistent object with factory create method.
  2. Save persistent object with save method.

The following codes demonstrate how to insert a Product record:

PersistentTransaction t = ErdPersistentManager.instance().getSession().beginTransaction();
try {
	Product product = ProductFactory.createProduct();
	product.setName("ABC Keyboard");
	product.setPrice(24.5);
	product.save();
}
catch (Exception e) {
	t.rollback();
}

Selecting records

Factory method provides a convinient listByQuery method, accept condition and order by as parameter` and return array of persistent object.

The following codes demonstrate how to select a list of Product records, null for condition parameter will select all records, null for order by parameter does not sort in any order:

Product[] products = ProductFactory.listProductByQuery(null, null);
for (int i = 0; i < products.length; i++) {
	System.out.println(products[i]);
}

Another useful method to select a persistent object by ID is loadByORMID. The following codes demonstrate how to select a lProuct record by ID.

Product product = ProductFactory.loadProductByORMID(1);

Updating records

  1. Select a persistent object from database.
  2. Update the persistent object.
  3. Save persistent object with save method.

The following codes demonstrate how to update a Product record:

PersistentTransaction t = ErdPersistentManager.instance().getSession().beginTransaction();
try {
	Product product = ProductFactory.loadProductByORMID(1);
	product.setName("DEF Keyboard");
	product.save();
}
catch (Exception e) {
	t.rollback();
}

Deleting records

  1. Select a persistent object from database.
  2. Delete persistent object with delete method.

The following codes demonstrate how to delete a Product record:

PersistentTransaction t = ErdPersistentManager.instance().getSession().beginTransaction();
try {
	Product product = ProductFactory.loadProductByORMID(1);
	product.delete();
}
catch (Exception e) {
	t.rollback();
}