• Home
  • RSS Feed
  • Log in

JPA implementation patterns: Using UUIDs as primary keys
Posted by Albert Sikkema at around evening time: June 3rd, 2009

Continuing Vincent Partington's blog series about JPA implementation patterns, I would like to add the following

The default way in JPA for primary keys is to use the @GeneratedValue annotation with the strategy attribute set to one of AUTO, IDENTITY, SEQUENCE, or TABLE. You pick the most appropriate strategy for your situation and that's it.
But you can also choose to generate the primary key yourself.

Using UUIDs for this is ideal and has some great benefits. In our current project we've used this strategy by creating an abstract base class our entities to inherit from which takes care of dealing with primary keys.

@MappedSuperclass
public abstract class AbstractBaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;
 
	@Id
	private String id;
 
	public AbstractBaseEntity() {
		this.id = UUID.randomUUID().toString();
	}
 
	@Override
	public int hashCode() {
		return id.hashCode();
	}
 
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof AbstractBaseEntity)) {
			return false;
		}
		AbstractBaseEntity other = (AbstractBaseEntity) obj;
		return getId().equals(other.getId());
	}
}

Using UUIDs versus sequences in general has been widely discussed on the web, so I won't go into too much detail here. But here are some pro's and con's:

Pros

  • Write this base class once and every entity gets an Id for free. If you implement equals and hashcode as above you also throw that one in as a bonus.
  • UUID are Universal Unique(what's in a name). This means that you get great flexibility if you need to copy/merge records from location a to b without having to re-generate keys. (or use complex sequence strategies).
  • UUIDs are not guessable. This means it can be safer to expose them to the outside world in let's say urls. If this would be good practice is another thing.

Cons

  • Performance can be an issue. See http://johannburkard.de/blog/programming/java/Java-UUID-generators-compared.html, Some databases don't perform well with UUIDs (at least when they are stored as strings) for indexes.
  • Ordering, Sorting. Speaks for itself.
  • JPA specific: you cannot test if a record has already been persisted by checking if the Id field has been set. One might argue if you need such checks anyway.

Conclusion

UUIDs are easy to use, but wouldn't it be nice if the JPA spec would open up to include UUID as a strategy? Some JPA implementations, like Hibernate, already have support for this:

@Id @GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid",
  strategy = "uuid")

For a list of all the JPA implementation pattern blogs, please refer to the JPA implementation patterns wrap-up.

  • Share/Bookmark

Filed under Hibernate, JPA, JPA implementation patterns, Java | 12 Comments »



12 Responses to “JPA implementation patterns: Using UUIDs as primary keys”



    Links Thread #1 - JEE, Seam, Performance, Maven Says:
    Posted at: June 8, 2009 at 7:24 am

    [...] JPA implementation patterns: Using UUIDs as primary keys (Albert Sikkema)Interessanter Ansatz mit Pro und Cons anstatt @GeneratedValue eine UUID in einer abstracten Oberklasse selbst zu generieren [Link] [...]



    Kenneth Says:
    Posted at: June 11, 2009 at 8:16 pm

    I might be missing something here but how is a private member “private String id” going to be inherited by any other classes?

    I also assume you left the getters and setters out for the sake of brievity? Not knocking anything, your article helped me significantly :)



    Jens Göring Says:
    Posted at: July 15, 2009 at 2:41 pm

    UUID.randomUUID() is not Universal Unique because it is based solely on random numbers (http://en.wikipedia.org/wiki/Uuid#Version_4_.28random.29). It might be improbable to get the same number twice locally, but you should not depend on *universal* uniqueness.

    If you need universal uniqueness, you have to rely on a third party UUID library like http://johannburkard.de/software/uuid/ or http://jug.safehaus.org/, which evaluate the network adapter’s MAC address to build a Version 1 UUID using platform dependend code.

    >UUIDs are not guessable

    If you use UUID Version 1 as mentioned above, this might not hold, see http://en.wikipedia.org/wiki/Uuid#Version_1_.28MAC_address.29

    I’ll like to add another Con:

    By using UUID, you introduce another dependency to your Domain class – this might be a problem if you for example want to transmit instances of these classes via Gilead to GWT client side code.

    I had this problem once and solved it by setting the UUID in the DAO’s insert/update method if it is null.



    Peter Schuler Says:
    Posted at: July 15, 2009 at 7:58 pm

    Ik think UUID’s certainly have their function. There are however big disadvantages in using them. A big disadvantage is database readabillity. Debugging your database is quit hard when you have to follow primary/foreign key’s based on UUID.

    For an interesting discussing about the opinion of the Hibernate developers see this post on the hibernate forum: https://forum.hibernate.org/viewtopic.php?t=967211.



    JPA Implementation Patterns « Fernando Franzini Java Blog Says:
    Posted at: July 16, 2009 at 1:11 pm

    [...] Using UUIDs as primary keys (guest blog by Albert Sikkema) [...]



    Fernando Machado Says:
    Posted at: July 21, 2009 at 4:21 am

    You can use UUIDs with EclipseLink as well.

    http://wiki.eclipse.org/EclipseLink/Examples/JPA/CustomSequencing



    Michael Dowling Says:
    Posted at: July 22, 2009 at 6:02 am

    Thanks for the article. I am a big believer in using UUIDs as primary keys for domain objects in the DB. Having used them quite a bit in my projects, I wanted to debate a couple of the cons:

    1. Performance can be an issue: Yes, it can, but grabbing a sequence from the DB creates a bigger issue (2 calls per new insert, depending on the RDBMS platform). This can be easily remedied by writing a simple UUID pool object which generates the UUIDs in batch, and doles them out on request. When the pool runs low/out, regenerate.

    2. Ordering/Sorting. Indeed, you really cannot order by the primary key in the case of a UUID. But then again, why does one usually order by primary key? Sequential primary keys tend to indicate the order of entity creation. Good DB design principles include having a created_date and a modify_date column as part of the entity (depending on your needs and requirements, of course, but I’d say this is mostly true). With this in mind, you CAN order by the create date.

    3. cannot test if a record has already been persisted by checking if the Id field has been set. Uhm, you can write a @GenericGenerator to generate the uuid if you’re using a JPA provider other than hibernate, and it wouldn’t be hard at all. The UUID is only set upon insert call to the DB, so you can do this check. But the OP is right, I question a design that checks for the existence of a PK being set.

    My $0.02. Reposting to my blog

    -Michael



    Response to: using UUIDs as primary keys | Michael Dowling’s Whispers Says:
    Posted at: July 22, 2009 at 6:17 am

    [...] using UUIDs as primary keys Tuesday, July 21st, 2009 | Java | michael So, I read someone’s blog post about the pros and cons of using UUIDs as primary keys.  I am a big believer in using UUIDs as [...]



    Chris Burnley Says:
    Posted at: July 23, 2009 at 6:15 am

    Should you put this in the constructor ? Isn’t the default constructor going to get executed indirectly via the JPA implementation when the entity is loaded from the database ?



    Albert Sikkema Says:
    Posted at: August 4, 2009 at 9:28 pm

    All,

    Really nice to see so many responses here. One of the things which triggered me to write this blog was that I always went for the ‘easy’ way in terms of selecting a primary key strategy without giving it much thought. I’m no UUID expert in any way although I found it very useful and I’ll use it again more often.

    @Micheal: Do you have an example of your pool implementation?

    @Jens: We felt comfortable to use the java.util.UUID implementation for our specific use-case, but I agree with you that for true universal uniqueness you should take a different implementation. Thanks for the links!



    Ralph Says:
    Posted at: September 2, 2009 at 1:44 pm

    Hi

    Instead of assign the uid inside the constructor you could use an EntityListener. This way the uid is only generated before persist or when somebody calls hashCode() or equals().

    @MappedSuperclass
    @EntityListeners({AbstractEntity.AbstractEntityListener.class})
    public abstract class AbstractEntity implements Serializable {

    @Id
    @Column(length=36)
    private String uid;

    @Override
    public boolean equals(Object o) {
    return (o == this || (o instanceof AbstractEntity && uid().equals(((AbstractEntity)o).uid())));
    }

    @Override
    public int hashCode() {
    return uid().hashCode();
    }

    String uid() {
    if (uid == null) {
    uid = new UUID().toString();
    }
    return uid;
    }

    public static class AbstractEntityListener {
    @PrePersist
    public void onPrePersist(AbstractEntity abstractEntity) {
    abstractEntity.uid();
    }
    }
    }



    cdiesse Says:
    Posted at: December 11, 2009 at 5:47 pm

    My main concern about defining Ids in MappedSuperClass, is to define the id but have opportunities to override the GeneratedValue strategy in derived classes.

    This is a missing feature in JPA 1.0 and JPA 2.0. Maybe this can be overcome with EntityListeners …

    Anythought ?



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Ajax Closures Functional Programming Seam Performance Scala Spring Architecture IntelliJ Scrum Lean esb Java XML Maven fitnesse Groovy qcon Semantic Web Testing product owner Agile Hibernate Poppendieck SOA Xebia Introduction to Agile Grails Agile Awareness Workshop JavaOne
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs