File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Preventing creation/update of entities in JPA Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Preventing creation/update of entities in JPA" Watch "Preventing creation/update of entities in JPA" New topic

Preventing creation/update of entities in JPA

Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

I have a case where one particular table is automatically generated by database triggers. I've mapped an entity to it, and I want to be able to retrieve these entities. But I don't want the application to be able to make any updates or insert any records.

What's the best practice for this in JPA2? I could label all the columns with updatable=false (and labelling them insertable=false might work as well, but I could see that not preventing inserting blank records), and I can make sure that there are no setter methods. But is there a better/simpler approach?

(I'm pretty new to JPA, so I could be missing something obvious).

James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
Setting each column to insertable or updateable =false is a very bad idea, these are only for columns that should not be written not rows.

In general the best solution is to not change your objects, if they are read-only then you should not change them, and they will not be updated.
If you wish to find bugs in your code that is incorrectly changing objects the best solution is probably to use events, a to pre/postPersist/Update events should work for this, just throw an error if any of these events is raised.
You could keep these events in development, and them remove them in production once you know your code is correct.

TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

Sounds sensible, thanks. I was wondering if there was a way of doing it declaratively, but if not that will do the trick.
I agree. Here's the link:
subject: Preventing creation/update of entities in JPA
It's not a secret anymore!