This snippet shows how to define and use auto-increment columns for generating primary keys for objects of a class. JDX does not set values of the corresponding columns through the INSERT and UPDATE statements used for storing or updating the instances of this class. However, the query operations do fetch the corresponding column values.
JDX also provides a named sequence generator facility that can alternatively be used to efficiently generate unique ids that you can assign to your objects before saving them in the database.
- package com.softwaretree.jdxandroidautoincrementexample.model;
- import java.util.Date;
- public class Employee {
- private int id;
- private String name;
- private Date DOB;
- private boolean exempt;
- private float compensation;
- /**
- *Default no-arg constructor needed for JDX
- */
- public Employee() {
- }
- // id field is generated by the database.
- public Employee(String name, Date DOB, boolean exempt, float compensation) {
- this.name = name;
- this.DOB = DOB;
- this.exempt = exempt;
- this.compensation = compensation;
- }
- // Other constructors and accessor (setter/getter) methods omitted
- CLASS com.softwaretree.jdxandroidautoincrementexample.model.Employee TABLE Employee
- PRIMARY_KEY id
- SQLMAP FOR id SQLTYPE 'INTEGER PRIMARY KEY AUTOINCREMENT'
- RDBMS_GENERATED id
- ;
- // Assuming jdxSetup of type JDXSetup has already been initialized.
- // Obtain ORM handles.
- JXResource jxResource = jdxSetup.checkoutJXResource();
- JXSession jxSessionHandle = jxResource.getJXSessionHandle();
- JDXS jdxHandle = jxResource.getJDXHandle();
- String employeeClassName = Employee.class.getName();
- DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd");
- dfm.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
- try {
- // Create and save a new employee Mark
- Employee emp = new Employee("Mark", dfm.parse("1981-01-01"), true, (float) 51001);
- jdxHandle.insert(emp, 0, null);
- // Create and save a new employee Bill
- emp = new Employee("Bill", dfm.parse("1982-02-02"), false, (float) 52002);
- jdxHandle.insert(emp, 0,null);
- // Retrieve all the employees
- List queryResults = jdxHandle.query(employeeClassName, null, JDXS.ALL, JDXS.FLAG_SHALLOW, null);
- // Retrieve employee Bill (name='Bill')
- queryResults = jdxHandle.query(employeeClassName, "name='Bill'", 1, JDXS.FLAG_SHALLOW, null);
- if (queryResults.size() == 1) {
- emp = (Employee) queryResults.get(0);
- // Change and update attributes of Bill
- emp.setExempt(true);
- emp.setCompensation((float) 52002.02);
- jdxHandle.update(emp, 0, null);
- }
- } catch (Exception ex) {
- Log.e("JDX", "Error", ex);
- throw ex;
- } finally {
- jdxSetup.checkinJXResource(jxResource);
- }