Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Id @GeneratedValue but set own ID value

I have a table with a generated id, but in some cases I would like to set it on my own. Can I, somehow, force Hibernate to ignore the @GeneratedValue?

like image 993
woezelmann Avatar asked Jan 21 '10 09:01

woezelmann


People also ask

What does @GeneratedValue annotation do?

Annotation Type GeneratedValueProvides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.

What is @GeneratedValue strategy GenerationType identity?

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql , you may specify auto_increment in the definition of table to make it self-incremental, and then use @GeneratedValue(strategy = GenerationType.IDENTITY)

What is @GeneratedValue annotation in spring boot?

You can change that by referencing the name of a @SequenceGenerator in the generator attribute of the @GeneratedValue annotation. The @SequenceGenerator annotation lets you define the name of the generator, the name, and schema of the database sequence and the allocation size of the sequence.

What is the use of @ID annotation?

The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation.


1 Answers

It may be an overkill but have you thought about writing your own CustomIDGenerator which probably subclasses say the AutoGenerator of hibernate and exposes a couple of methods where you can set the id of the next class object to be generated so for example

class MyGenerator extends .... {  public void setIdForObject(Class clazz, Long id) {     //once you use this API, the next time an object of      //type clazz is saved the id is used }  public void setIdForObject(Class clazz, Long id, Matcher matcher) {     //once you use this API, the next time an object of      //type clazz is saved and the matcher matches yes the id will be      //assigned. Your matcher can match properties like name, age etc     //to say the matched object } } 

This could get complicated but at the least is possible as per hibernate doco

like image 109
Kannan Ekanath Avatar answered Sep 20 '22 18:09

Kannan Ekanath