-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Best practices for "find or create" operations.
PostPosted: Thu Nov 10, 2011 5:51 pm 
Beginner
Beginner

Joined: Sun Jan 11, 2009 2:47 pm
Posts: 21
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.

  1. load() + persist() if not found, as in the above example.
  2. Construct the object I'm looking for then use merge().
  3. 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.
  4. 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!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.