Discussion:
[h2] Spring Boot Persistable<ID> interface behaviour: when testing with in-memory H2, no DataIntegrityViolationException is thrown when duplicated instance is saved, and "isNewObject" always set to "true"
w***@gmail.com
2018-10-26 11:12:02 UTC
Permalink
I submitted this issue at:

https://github.com/h2database/h2database/issues/1391


and redirected here.



In Spring, there is an interface
"org.springframework.data.domain.Persistable<ID>", which helps to mark the
"insertability/updatibility" of an entity. It requires the implementation
of two methods:

public interface Persistable<ID extends Serializable> extends Serializable {


/**
* Returns the id of the entity.
*
* @return the id
*/
ID getId();


/**
* Returns if the {@code Persistable} is new or was persisted already.
*
* @return if the object is new
*/
boolean isNew();
}

If is new, the object should be persisted; otherwise the DB should update
it.

Usually, we use this snippet to implement it:

@Transient
private boolean isNewObject;


@Override
public boolean isNew() {
return isNewObject;
}

We change `isNewObject` to change the behavior of DB. `isNewObject` to the
behavior of DB.

Why we need it? Because we want to first save, then if there was some
duplication, we catch an
DataIntegrityViolationException
and change `isNewObject()` to `false` and `save()` again, then the update
will be performed, instead of doing a full-table "select" (exist() check,
etc) before saving.


When testing in PostgreSQL, it works; but with in-memory H2, there is no
exception thrown, and `isNew`, after persisting any object, will be changed
to "true".


Is this interface taken into consideration in H2? I ask to confirm; if is
not, I will try to use PostgreSQL(the real DB engine) in my testing,
although I want to use H2 in-memory DB when doing a minimal integration
tests because it is supposed to be faster.
--
You received this message because you are subscribed to the Google Groups "H2 Database" group.
To unsubscribe from this group and stop receiving emails from it, send an email to h2-database+***@googlegroups.com.
To post to this group, send email to h2-***@googlegroups.com.
Visit this group at https://groups.google.com/group/h2-database.
For more options, visit https://groups.google.com/d/optout.
Loading...