In my application I am frequently performing find-or-create type operations on entities, as in the following pseudocode:
Code:
Entity findOrCreate (id) {
Entity e = load(id);
if (e not found) {
e = new Entity();
persist(e);
}
return e;
}
There are a few ways I can think of to do this.
- load() + persist() if not found, as in the above example.
- Construct the object I'm looking for then use merge().
- Load a local set of all objects, and search in that set for what I'm looking for. Create, persist(), and add to local set if not found.
- Use a Hibernate managed collection such as a set, searching and adding as appropriate.
I find the merge() solution to be the cleanest as far as coding. Are their any significant pros and cons to the above options, or any other options I have? What is the best practice here? Are there any performance/consistency considerations when dealing with objects with composite primary keys? Issues with cascades? Foreign key consistency and references? Etc.
Thanks!