4

Is there any way to find out if an entity was read from the database or not?

This question is related to How to know if a detached JPA entity has already been persisted or not?. But the workaround to check its primary key does not answer my question. It would not work for entities which get their primary keys read from an import file or so.

To extend the question:

How do JPA implementations determine if an entity is to be inserted or updated?

Community
  • 1
  • 1
Jemolah
  • 1,962
  • 3
  • 24
  • 41

2 Answers2

4

Hibernate uses the value of the field annotated with @Version (for optimistic locking), if present, to tell if an entity is transient or detached. You could do the same.

Otherwise, no, there's no way. A POJO is a POJO. And Hibernate uses the value of the primary key if no @Version field is present.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Interesting answer. How does @Version help there? – Jemolah May 20 '13 at 10:40
  • The @Version field is set by JPA: it's incremented each time the entity is inserted/updated in the database. So if it's null (or 0), it means the entity has never been inserted. If it's not, it means that it has been saved already. – JB Nizet May 20 '13 at 10:43
  • Ah. Thx. Good point. Well. You are right. A POJO is a POJO. Nevertheless we are not talking about POJO's but about annotated JPA entities. As I already stated, the primary key is not a good approach. – Jemolah May 20 '13 at 10:51
  • And annotated JPA entities are POJOs. When you construct `new Car(someId)`, JPA has absolutely no way to know if the car exists in the database or not. All it knows is that, since the ID is supposed to be auto-generated, is someId is not null, then the entity has been inserted, some time ago, in the database, but could very well not exist anymore if it has been deleted. – JB Nizet May 20 '13 at 10:55
  • Thanks for this discussion. Based on JPA there is no proper way to find this out. There are workarounds for cases where you can rely on @ Version or @ Id. So the only proper solution is to have all JPA entities extend an (abstract) base class which contains a field "boolean isNew = false;" and set this to true whenever an entity is instantiated during an import or any GUI frontend activity. – Jemolah May 20 '13 at 11:27
1

To know if an Entity instance is currently managed by a given EntityManager instance you have the myEntityManager.contains(myEntity) method, it may do the trick for you, even if i suppose than most of implementation are based on primary key state (JB Nizet is perfectly right).

Note that return false does not assert that entity is not present in database. This just check if the entity is managed or not, it could have come from database and been detached or being retrieved by another EntityManager instance.

Gab
  • 7,869
  • 4
  • 37
  • 68