Chapter 16. Sequence

Sequences are simple value generators. As we saw in Chapter 15, Mapping Metadata, sequences are typically used to automatically create identity or field values for persistent objects. At times, however, you may want to use a sequence directly though JDO's Sequence interface.

public Sequence getSequence (String name);

Chapter 15, Mapping Metadata demonstrated how to define a named sequence in metadata. The PersistenceManager's getSequence method retrieves a sequence by its fully qualified name. If no sequence with the given name exists, the PersistenceManager throws a JDOUserException.


In Kodo, you can also obtain the identity sequence of a class or the value sequence of a field through the kodo.jdo.KodoJDOHelper.

public Object next ();
public Object current ();
public long nextValue ();
public long currentValue ();

The method returns the next value in the sequence. The type of the return value will depend on the sequence type, as defined in metadata. In JDOR, most JDO sequences are front-ends for native database sequences, which have integral return types, such as Long.

Invoking current returns the current sequence value, which is also typically the last sequence value used. Some sequences cannot access their current value without incrementing it, or do not track their current value. Calling current on these sequences returns null.

nextValue and currentValue are convenience methods for sequences that return integral values. They are equivalent to invoking:

((Long) next ()).longValue ()
((Long) current ()).longValue ()
public void allocate (int additional);

This method is a hint that you will be requesting additional sequence values in the near future. The implementation might optimize by generating the needed sequence values in batch.

Example 16.1. Using Sequences

PersistenceManager pm = ...;
Sequence seq = pm.getSequence ("org.mag.subscribe.ContractSeq");
seq.allocate (1000);    // hint for efficiency
for (int i = 0; i < 1000; i++)
    long contractId = seq.nextValue ();
    pm.makePersistent (generateContract (contractId));


Skip navigation bar   Back to Top