micronaut-projects / micronaut-data

Ahead of Time Data Repositories
Apache License 2.0
466 stars 197 forks source link

Repository update does not work as upsert when using @Where on entity or repository #1243

Open nfode opened 2 years ago

nfode commented 2 years ago

Expected Behavior

When using @Where on an entity or a repository, the update method should also create an entity if it does not exist. This behavior exists when using an entity + repository without any @Where Annotations, and also worked with @Where annotations in the micronaut-data version 3.0.1 (micronaut 3.0.2).

Actual Behaviour

When using @Where either on the entity or the repository, update does not persist an entity if it has not existed before.

Here are some tests: https://github.com/flip-corp/micronaut-bugreports-demo/blob/update_does_not_save_anymore/src/test/kotlin/com/example/db/UserRepositoryTest.kt

All of them should pass, but all except the one using a repository and entity without @Where fail.

Steps To Reproduce

  1. Checkout https://github.com/flip-corp/micronaut-bugreports-demo/tree/update_does_not_save_anymore
  2. Run the tests here: https://github.com/flip-corp/micronaut-bugreports-demo/blob/update_does_not_save_anymore/src/test/kotlin/com/example/db/UserRepositoryTest.kt

Environment Information

Example Application

https://github.com/flip-corp/micronaut-bugreports-demo/tree/update_does_not_save_anymore

Version

micronaut 3.2.0 and micronaut-data 3.2.1

dstepanov commented 2 years ago

Not sure if this is a bug, the problem here is that we are using EntityManager#merge for the update operation. When you define @Where we are creating a custom update query and trying to execute it, otherwise merge is invoked.

I think choosing merge operation by default for the update wasn't the best decision, we should probably revisit it in the next major version and use Session#update.