3

I'm new to JPA and have noticed that one can make use of optimistic locking by annotating a field in an entity with @Version. I'm just curious about whether persistence providers will create an implicit version field if there doesn't exist one before. For example the website of objectdb states:

"When using ObjectDB, optimistic locking is enabled by default and fully automatic."

But this seems to be vendor-specific behaviour since optimistic locking won't be enabled by default in EclipseLink, for example. So if I want to use locking (and yes, I want :-) ), am I required to create an extra attribute for all my entities? Are there any hints in the specification?

Thank you in advance!

ObjectDB
  • 1,294
  • 7
  • 8
tsh
  • 183
  • 1
  • 2
  • 11

1 Answers1

3

Yes, the JPA @Version annotation allows you to define a version property, I assume ObjectDB just creates a this property by default.

Your own property can be an Integer, Long or Short (or their primitive equivalents), or a java.sql.Timestamp.

Most JPA providers I'm aware of only do optimistic locking if you explicitly use the @Version annotation.

MattR
  • 6,128
  • 2
  • 18
  • 28
  • Well, I feared that. What I actually want to achieve is to lock all entities in arbitrary queries, but without making assumptions of the state of the entity model and without knowing the actual persistence provider. – tsh Dec 04 '12 at 07:20
  • Optimistic locking doesn't actually "lock" the record, if you want a real lock you need to look at pessimistic locking. – MattR Dec 04 '12 at 07:24
  • And I think you'd be safe using `@Version` on a property of type long if you want portability. – MattR Dec 04 '12 at 07:25
  • I understand, but let's assume I don't know the entity model, but I want to set locks (more in the context of a library than my own application) – tsh Dec 04 '12 at 07:30
  • 1
    Then you could use pessimistic locking (explicitly locking records via the EntityManager). – MattR Dec 04 '12 at 07:37