JPA : Class Mapping

The first thing to decide when implementing your persistence layer is which classes are to be persisted. If you need to persist a field/property then you must mark that class as persistable. In JPA there are three types of persistable classes.

  • Entity - persistable class with full control over its persistence.
  • MappedSuperclass - persistable class that will not be persisted into its own table simply providing some fields to be persisted. Consequently an inheritance tree cannot just have a mapped superclass on its own. Read more
  • Embeddable - persistable class that is only persistable embedded into an entity class. Read more

Let's take a sample class (Hotel) as an example We can define a class as persistable using either annotations in the class, or XML metadata.

To achieve the above aim with XML metadata, we do this

<entity class="org.datanucleus.test.Hotel">
    ...
</entity>

Alternatively, using JPA Annotations, like this

@Entity
public class Hotel
{
    ...
}

In the above example we have marked the class as an entity. We could equally have marked it as mapped-superclass (using annotation @MappedSuperclass, or XML element <mapped-superclass>) or as embeddable (using annotation @Embeddable, or XML element <embeddable>).

See also :-

Persistence Aware

With JPA you cannot access public fields of classes. DataNucleus allows an extension to permit this, but such classes need special enhancement. To allow this you need to

  • Annotate the class that will access these public fields (assuming it isn't an Entity) with the DataNucleus extension annotation @PersistenceAware

You perform the annotation of the class as follows

@PersistenceAware
public class MyClassThatAccessesPublicFields
{
    ...
}

See also :-

Read-Only

You can, if you wish, make a class read-only. This is a DataNucleus extension and you set it as follows

@Entity
@Extension(vendorName="datanucleus", key="read-only", value="true")
public class MyClass
{
    ...
}