Monday, February 5, 2007

Read-Only JPA Entities

This came up on the TopLink Forum last week but for those who don't read all the postings I thought I'd repeat the information here.

The question was whether it's possible to have read-only Entities in JPA. This isn't in the spec but is possible in TopLink Essentials. You do it by calling the setReadOnly() method on an Entity's TopLink descriptor. One way to do this is through a descriptor customizer.

For example, in persistence.xml:

<property
  name="toplink.descriptor.customizer.Title"
  value="comics.toplink.TitleCustomizer"/>


And a definition of TitleCustomizer implementing oracle.toplink.essentials.tools.sessionconfiguration.DescriptorCustomizer.

public class TitleCustomizer implements DescriptorCustomizer {

public void customize(ClassDescriptor desc) throws Exception {
desc.setReadOnly();
}
}


The semantics of read-only are that any changes you make to an object will not be written to the database, but you are not prevented from making changes.

--Shaun

3 comments:

Somatik said...

thanks for the tip!

Ron said...

I'm kind of new to Toplink, but why not just set the updatable and insertable values on the @Column annotation to false?

Ron

Shaun Smith said...

By marking the entire object read-only you get the same result as marking each @Column non-updatable and non-insertable but you also save all the processing required to determine what has changed on an Entity. Read-Only classes are not included in this calculation. This can be significant if you're dealing with large numbers of objects.

--Shaun