How to always generate an upsert query?

Suppose I have following table structure (postgresql)

create table zar
(
    id           serial
        constraint zar_pk
            primary key,
    email        text not null
        constraint zar_pk_2
            unique,
    profile_name text not null
);

respective entity class

@Entity
public class Zar {
    @Id
    @GeneratedValue(generator = "zar_is_seq")
    @SequenceGenerator(name = "zar_id_seq", sequenceName = "zar_id_seq", allocationSize = 1)
    private long id;
    private String email;
    private String profileName;
    // getter/setter omitted for brevity
}

basically a generic table with unique constraint on a parameter that is not managed by the system managing this table (be it email, ssn, so on). The system works by fully replacing the record in case there’s a conflict (last write must always win). With regular sql I would write the query as follows:

insert into zar(email, profile_name) values(?, ?) on conflict do update set (profile_name) = (excluded.profile_name) returning *

But how do I get hibernate to generate such query (on conflict of unique parameters to always update other parameters)? In one of vlad’s blog posts I saw that there is a merge method, but from the logged sql it still seems to fetch the record under the hood (which might not exist) and performs an insert or an update depending on whether a record was returned (which is prone to races). I suppose I can prefetch the record if it exists with LockMode.PESSIMISTIC_WRITE (an equivalent of select ... for update), but this doesn’t solve a problem where the row does not exist, because this does not provide an exclusive lock on row that would be created by tx. Using a dedicated query via @SQLInsert(sql = "...") works in this simple case (and it’s rather brittle because you need to manage the query yourself every time a new column is added), but breaks when there’s a one to many relationship being persisted as a tree.

I have found an interface that could solve my problems called JpaConflictUpdateAction but I am not sure how to provide it to the entity manager besides writing my own Criteria<T> query, which isn’t feasable due to hibernate being hidden away behind spring data jpa in actual application.

Is it possible to always generate insert ... on conflict do update... statement?

I don’t know why you think Hibernate ORM is hidden away, but maybe you should start at removing this thinking barrier and make use of the technology that is underneath your Spring Data API.

You can either construct an insert statement manually with Hibernate ORM JPA Criteria extensions, or you use the Hibernate ORM StatelessSession API to call upsert for your entity, which will also make use of insert ... on conflict ... on PostgreSQL.

“Just use upsert” doesn’t really work because I do not know the original ID of the object, and StatelessSessiomImpl#idToUpsert(Object, EntityPersister) checks whether an object is already managed by persistence context.

	protected Object idToUpsert(Object entity, EntityPersister persister) {
		final Object id = persister.getIdentifier( entity, this );
		final Boolean unsaved =
				persister.getIdentifierMapping()
						.getUnsavedStrategy()
						.isUnsaved( id ); // true, when id == 0L 
		if ( unsaved != null && unsaved ) {
			throw new TransientObjectException( "Object passed to upsert() has an unsaved identifier value: "
					+ persister.getEntityName() );
		}
		return id;
	}

And if I were to use sample entity above the generated query checks conflict only on field annotated with @Id rather than the unique constraint that is String email, which poses the question in the first place: how to signal hibernate that it should generate on conflict(email)which is not an @Id field.

Ah, I missed the conflict(email) part, sorry. In that case, I would say that the it’s best to write this insert ... conflict query by hand. You can even use HQL for that, no need to use JPA Criteria: Hibernate ORM User Guide

The thing is, you won’t be able to retrieve the generated sequence identifier and will have to query the row afterwards by email until we add support for the returning clause also in HQL: HHH-19405

So, you could write your repository like:

@Repository
interface MyRepo {
  @ModifyingQuery
  @Query("insert into Zar (email, profileName) values (?1, ?2) on conflict (email) do update set profileName = excluded.profileName")
  int upsertZar(String email, String profileName);
}

Makes sense. Are there any plans to add support to indicate what fields can the entity conflict on?

What do you mean? You can specify the attributes that can cause a conflict, just like with PostgreSQL native syntax and Hibernate ORM will translate that accordingly.

I mean without having to define a custom query. Much like we can indicate with @Column annotation to write field values to specific columns in case their names do not match, or @JoinColumn to indicate which column is used to identify the foreign key relationship, i’d expect there to be something like @Unique(columns={"email"}, conflict=ConflictAction.UPDATE_ALL) (columns here being an array because there can be multiple fields that make a row unique) at either entity or field level to indicate that a full replacement should be generated.

It’s an interesting idea. Since the primary key identifier is vital for the persistence context to identify the entity instance, I could only imagine this kind of behavior to fit with the IDENTITY generation, since that would force an early insert for such entities. With SEQUENCE generation, it would potentially waste a lot of sequence values, which may be ok for you, but not sure if we should encourage something like that. Also, we’d have to implement early inserts for such sequence based entities and handle identifier replacement, which is not trivial.

Overall, I like the idea and I think you should create a Jira ticket for it as well as start a discussion in our Zulip chat platform to see what others think.

One small thing worth knowing if you go with the hand-written insert … on conflict query: on PostgreSQL the sequence still advances on every attempt, even when the row ends up being updated instead of inserted. So with a “last write wins” table that gets hit often, you will see gaps in the ids. That is harmless, but it is the same waste beikov mentioned, just happening on the database side.

If the email is really the business key, mapping it with @NaturalId also helps on the read side. After the upsert you can load the row with session.byNaturalId(Zar.class).using(“email”, email).load() instead of a separate query, and Hibernate can cache the natural id to primary key lookup.