My goal is to create an entity Device that has a unique field IMEI and I would like to use it as a primary key, and specify it at device registration time (manually specified, while creating the entity). I use Spring roo tool for development and hibernate as ORM.
When I specify this in Entity declaration:
@RooJavaBean
@RooToString
@RooJpaActiveRecord(identifierField = "IMEI", identifierType = String.class)
public class Device {...}
I get this generated:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "IMEI")
private String Device.IMEI;
While deploying project to server with mysql db i get this error:
2013-03-17 20:03:23,136 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: create table device (imei varchar(255) not null auto_increment, model varchar(255), name varchar(255) not null, version integer, primary key (imei))
2013-03-17 20:03:23,136 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Incorrect column specifier for column 'imei'
Then I override roo generated field with
@Id
@GeneratedValue(generator = "org.hibernate.id.Assigned")
@Column(name = "the_code")
private String code;
(I've found this in here)
But still get error. Then I've changed code simply to this:
@Id
private String IMEI;
and then it works fine and asks me to specify imei field before saving entity.
My questions are:
Is it correct to use my custom field as id?
Is it ok to by String?
is it ok that it is not generated with hibernate but taken from the device imei?
What is org.hibernate.id.Assigned?
Why roo generated code for @RooJpaActiveRecord(identifierField = "IMEI", identifierType = String.class) does not work?
Is it posible to create String auto generated primary key?
What is default GeneratedValue strategy value (my last case)?
I've readofficial doc but didn't understand all, please refer me to article where i can read about all this.
Thanks, sorry for long question.
A straightforward solution could be to use the @PrePersist
annotation on your entity class.
Simply add the method
@PrePersist
private void ensureId(){
this.setId(UUID.randomUUID().toString());
}
and get rid of the @GeneratedValue
annotation.
PrePersist documentation: http://docs.oracle.com/javaee/5/api/javax/persistence/PrePersist.html
Stefano