'How to tell what action was taken by the JPA save method

I have a repo:

public interface SomeRepository extends CrudRepository<SomeClass, Long> {
    SomeClass findById(Long id);
}

and I need to save objects to it:

SomeClass someClass = GetAMaybeNewSomeClass();
someClass = someRepository.save(someClass);

how do I tell, in code, what operation the save call did? I need to know if someClass already existed in the database, and if it did exist, I need to know if the call to save actually changed it.

I could do this by calling findById before the save operation and comparing what I find with what I'm saving, but I'd rather use something built in to the framework if it exists.



Solution 1:[1]

The save operation in Spring combine the persist and the merge methods, the source code of that method is:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

So, know exactly what operation the framework does when you call the save method I think is not possible, so If you do need to know, you should use persist and merge methods directly from JPA or create your own methods.

UPDATE:

You can also use existsById method from CrudRepository

Solution 2:[2]

You could use a MappedSuperClass base entity that contains a method that returns a flag based on whether the entity is new or not, following a pattern shown in the Spring docs here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Woodchuck