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 following annotations on your class

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

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.

Object id = JDOHelper.getObjectId(obj);

You should be aware however that the "identity" is in a complicated form, and is not available as a simple integer value for example. Again, if you want an identity of that form then you should use application identity

DataNucleus Implementation

When implementing datastore identity DataNucleus provides a public class that represents this identity. If you call JDOHelper.getObjectId(...) for a class using datastore identity you will be passed an object which, in the case of DataNucleus will be of type org.datanucleus.identity.OIDImpl . If you were to call "toString()" on this object you would get something like

This is made up of :-
    1 = identity number of this object

DataNucleus allows you the luxury of being able to provide your own datastore identity class so you can have whatever formatting you want for identities.

Accessing objects by Identity

You can also access the object from the object class name and the toString() form of the datastore identity (e.g "101[OID]mydomain.MyClass") like this

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

or in "datanucleus-api-jpa" 3.0.7+ you can also just pass in the "key" value, like this

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