JPA : Persistent Fields or Properties

Now that we have defined the class as persistable we need to define how to persist the different fields/properties that are to be persisted. Please note that JPA cannot persist static or final fields . There are two distinct modes of persistence definition; the most common uses fields , whereas an alternative uses properties .

Persistent Fields

The most common form of persistence is where you have a field in a class and want to persist it to the datastore. With this mode of operation DataNucleus will persist the values stored in the fields into the datastore, and will set the values of the fields when extracting it from the datastore.

Requirement : you have a field in the class. This can be public, protected, private or package access, but cannot be static or final.

An example of how to define the persistence of a field is shown below

@Entity
public class MyClass
{
    @Basic
    Date birthday;

    @Transient
    String someOtherField;
}

So, using annotations, we have marked this class as persistent, and the field birthday also as persistent, whereas field someOtherField is not persisted. Using XML MetaData we would have done

<entity name="mydomain.MyClass">
    <attributes>
        <basic name="birthday"/>
        <transient name="someOtherField"/>
    </attributes>
</entity>

Please note that the field Java type defines whether it is, by default, persistable. Look at the Types Guide and if the type has a tick in the column "Persistent?" then you can omit the "basic" specification.



Persistent Properties

A second mode of operation is where you have Java Bean-style getter/setter for a property . In this situation you want to persist the output from getXXX to the datastore, and use the setXXX to load up the value into the object when extracting it from the datastore.

Requirement : you have a property in the class with Java Bean getter/setter methods. These methods can be public, protected, private or package access, but cannot be static. The class must have BOTH getter AND setter methods.

An example of how to define the persistence of a property is shown below

@Entity
public class MyClass
{
    @Basic
    Date getBirthday()
    {
        ...
    }

    void setBirthday(Date date)
    {
        ...
    }
}

So, using annotations, we have marked this class as persistent, and the getter is marked as persistent. By default a property is non-persistent, so we have no need in specifying the someOtherField as transient. Using XML MetaData we would have done

<entity name="mydomain.MyClass">
    <attributes>
        <basic name="birthday"/>
    </attributes>
</entity>