This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Preventing creation/update of entities in JPA

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

Thanks.
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Events
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds sensible, thanks. I was wondering if there was a way of doing it declaratively, but if not that will do the trick.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic