JPA : Datastore Identity

While JPA defines support for application identity only DataNucleus also provides support for datastore identity. With datastore identity you are leaving the assignment of id's to DataNucleus and your class will not have a field for this identity - it will be added to the datastore representation by DataNucleus. It is, to all extents and purposes a surrogate key that will have its own column in the datastore. To specify that a class is to use datastore identity with JPA, you define the metadata as follows

<entity class="org.mydomain.MyClass">
    <datastore-id/>
    ...
</entity>

or using annotations, for example

@Entity
@org.datanucleus.api.jpa.annotations.DatastoreIdentity
public class MyClass
{
    ...
}

Please note that since the JPA XML metadata is poorly designed it is not possible to specify datastore identity using XML, you have to use the annotations.

When you have an inheritance hierarchy, you should specify the identity type in the base class for the inheritance tree. This is then used for all persistent classes in the tree.

Generating identities

By choosing datastore identity you are handing the process of identity generation to the DataNucleus. This does not mean that you haven't got any control over how it does this. JPA defines many ways of generating these identities and DataNucleus supports all of these and provides some more of its own besides.

Defining which one to use is a simple matter of adding a MetaData element to your classes definition, like this

@Entity
@org.datanucleus.api.jpa.annotations.DatastoreIdentity(generationType=GenerationType.TABLE)
public class MyClass
{
    ...
}

See also :-


Accessing the Identity

When using datastore identity, the class has no associated field so you can't just access a field of the class to see its identity - if you need a field to be able to access the identity then you should be usingapplication identity. There are, however, ways to get the identity for the datastore identity case, if you have the object.

import org.datanucleus.api.jpa.NucleusJPAHelper;

Object idKey = NucleusJPAHelper.getDatastoreIdForEntity(obj);

From this you can use the "find" method to retrieve the object

Object obj = em.find(MyClass.class, idKey);