12

what's the easiest way to implement a string id in jpa ? So far what I have is

@Id
@GeneratedValue
private int id;

and what I'd like to have is something like

@Id
@GeneratedValue
private String id;

but if I use it like this, I get 'this id generator generates long, integer, short'.

Car981
  • 261
  • 1
  • 3
  • 11

2 Answers2

20

You can create the UUID from Java like this:

UUID.randomUUID().toString();

Or if your JPA supports it, like Hibernate does, you can use:

@Id @GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String myId;

Checkout this blogpost for details.

If you google for "JPA UUID" there are many alternatives.

Alex
  • 2,953
  • 1
  • 27
  • 37
2

If you are using EclipseLink, you can use the @UuidGenerator,

http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_uuidgenerator.htm#CFAFIIFC

You should also be able to convert a sequence integer to a string if desired.

James
  • 17,965
  • 11
  • 91
  • 146