The other answers give good solutions to the problem. I'll try to summarise the various approaches, to give a good overview.
Support in JPA
I'd like to write a method [...] that returns an object of the
provided class if one exists in the database with pk primaryKey, and
otherwise creates a new object of that class, persists it and returns
it.
The very next thing I'll do with the object will be to update all its
fields, within a transactio
This is a reasonably common situation, and there is a name for this operation: Upsert (blend word of UPDATE and INSERT) - meaning insert a record if it is not present (decided by its key), update if it is present.
Most relational database systems have built-in support for this, either via the standard SQL keyword MERGE, or some other keyword - see the Wikipedia article for MERGE for details. This allows performing an upsert with a single SQL statement.
Is there an idiomatic way to do this in JPA, or is there a better way
to solve my problem?
Unfortunately: no. JPA itself does not support an upsert operation. There is no UPSERT or MERGE or similar keyword in JPQL, or in the JPA API. More precisely: EntityManager.merge()
will do what you want in a single-threaded solution (find &update the entity or insert it), but it is not thread-safe.
However, there are some workarounds (some explained in other answers).
Workarounds
Insert and catch constraint violation
Make sure that there is a unique index for the key field(s) that you want to use. Then just naively perform an insert, using EntityManager.persist()
. If the record was not present, it will be inserted. If the record was already present, you will get an Exception, which you can catch. Then you can perform an UPDATE (using EntityManager.merge()
) instead.
This is described in more detail in Pace's answer.
Advantage: No complicated native SQL required.
Disadvantage: The exception handling will be quite nasty, because JPA also does not have a portable way to distinguish wether an exception was caused by a constraint violation (which would be ok here) or by some other problem (dead database, network error) which you would still want to handle.
Use MERGE / UPSERT statement
You can use a native query to execute a MERGE or UPSERT statement, using the DB's built-in support for performing upserts.
Advantage: The cleanest solution from the DBMS point of view, as it uses the mechanism that the DBMS offers for this problem.
Disadvantage: Somewhat nasty native SQL required; basically "going behind JPA's back".
See Using Merge statement for single table for details.
Use DB lock
You can also use a form of pessimistic locking, by acquiring a database lock on some record (using EntityManager.lock()
). Which record to lock will be application-specific. Typically, if you have a 1:n relationship, and you are inserting into the :n table, you would lock the corresponding "main" record.
For example, when adding a new item to an invoice, you would lock the main invoice record. After obtaining the lock, you check for existence of the record, and update or insert it.
If all code that performs inserts respects this, the locking will make sure that once you have acquired a lock, no other process/thread can interfere.
The acquisition of the lock and the update/insert must be put inside a transaction (the end of the transaction will automatically release the lock).
Advantages: No native SQL required. Can be faster than the other solutions in some cases (though this depends on specifics).
Disadvantages: May reduce performance, because other code has to wait for the lock. In particular, the DBMS may decide to lock the whole table instead of just one row, which will make this worse. If you get the locking wrong, you could create potential deadlocks.
Recommendation
In my experience, using MERGE / UPSERT is usually the best solution, as it optimally uses the resources provided by the DBMS. The required native SQL is a bit ugly, and you must make sure not to accidentally persist via JPA, but apart from that it's the cleanest (and usually the fastest) solution.
If that is not practical, the "insert and catch" approach can also work - but it also has ugly code (the exception handling), and again, you must make sure to always apply this exception handling.
Using locks is helpful in some situations, but I'd use it as a last resort.
Remarks
- There is actually a bug for EclipseLink (one JPA implementation) to provide support for upsert - Bug 344329 - Add support for UPSERT/MERGE. However, the bug is from 2011 and nothing seems to have happened. Also, this would ideally be added to the JPA specification, which does not seem to be happening either.
- A simple solution to the problem is to make sure only a single thread/process is doing the inserting/updating - then you can just naively update and insert. But that is not always practical :-).