Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

spring mvc - How to make string primary key hibernate. @GeneratedValue strategies

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...