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.
精彩评论