Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string id generator

Tags:

jpa

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'.

like image 417
Car981 Avatar asked Dec 04 '12 10:12

Car981


2 Answers

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.

like image 106
Alex Avatar answered Oct 19 '22 08:10

Alex


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.

like image 2
James Avatar answered Oct 19 '22 08:10

James