开发者

CRUD and merge/persist

开发者 https://www.devze.com 2023-01-29 19:40 出处:网络
I am working on an interface for making CRUD operations using JPA, and the following question formed in my head.

I am working on an interface for making CRUD operations using JPA, and the following question formed in my head.

If I use persist for my create method, then I can catch an EntityExistsException, if the method is called with an object that has an ID already in the database.

In the update method I will then use merge for saving changes. In order not to create something that does not exists I was thinking about looking it up first, and throwing an exception if it is not found in the database.

Now I am just thinking that this might be overkill, and why not just let merge create it if does not exists and update it if it does? But then what do I need the create method for then?

So what do you think? Is it best practice to have a create method that only creates and throws an exception when trying to create something already in the database, and have an update method that only lets you update something that already exists and therefore never creates?开发者_StackOverflow社区


I'd use just merge. If you understand (and document in your code) what it is doing, it is a good option. I've used it on several projects without any problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消