You are here: Platform Specific Issues > Disconnected Objects > Comparison Of Different IDs > Example ID-Generator

Example ID-Generator

This example demonstrates how you can use an ID-generator to identify objects across objects containers. Take a look advantages and disadvantages of ID-generators: See "Comparison Of Different IDs"

This example assumes that all object have a common super class, IDHolder, which holds the id.

private int id;
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}
IDHolder.java: id holder

Don't forget to index the id-field. Otherwise finding objects by id will be slow.

configuration.common().objectClass(IDHolder.class).objectField("id").indexed(true);
AutoIncrementExample.java: index the id-field

The hard part is to write an efficient ID-Generator. For this example a very simple auto increment generator is used. Use the creating-callback-event in order to add the ids to the object. When committing, store the state of the id-generator.

final AutoIncrement increment = new AutoIncrement(container);
EventRegistry eventRegistry = EventRegistryFactory.forObjectContainer(container);
eventRegistry.creating().addListener(new EventListener4<CancellableObjectEventArgs>() {
    public void onEvent(Event4<CancellableObjectEventArgs> event4,
                        CancellableObjectEventArgs objectArgs) {
        if(objectArgs.object() instanceof IDHolder){
            IDHolder idHolder = (IDHolder) objectArgs.object();
            idHolder.setId(increment.getNextID(idHolder.getClass()));
        }
    }
});
eventRegistry.committing().addListener(new EventListener4<CommitEventArgs>() {
    public void onEvent(Event4<CommitEventArgs> commitEventArgsEvent4,
                        CommitEventArgs commitEventArgs) {
        increment.storeState();
    }
});
AutoIncrementExample.java: use events to assign the ids

The id is hold by the object itself, so you can get it directly.

IDHolder idHolder = (IDHolder)obj;
int id = idHolder.getId();
AutoIncrementExample.java: get the id

You can get the object you can by a regular query.

Object object = container.query(new Predicate<IDHolder>() {
    @Override
    public boolean match(IDHolder o) {
        return o.getId() == id;
    }
}).get(0);
AutoIncrementExample.java: get an object by its id