views:

450

answers:

4

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?

A: 

Why would you like to set the id sometimes yourself? What usecase do you try to solve?

Hardy
It is not an answer.
Arthur Ronald F D Garcia
on startup I want to set a 'no User' with id 0
woezelmann
+1  A: 

For you use case, you can manually add this no user. One way to do it is to put the insert operation on a file named "./import.sql" (in your classpath). Hibernate will go execute these statements when the SessionFactory is started.

Emmanuel Bernard
@Emmanuel Bernard He said: **but, in some cases,** i would like to set it on my own. If you define how Hibernate should save an Entity (through "/.import.sql" file), so its automatic generation of identifier will not work, do not ?
Arthur Ronald F D Garcia
No it's unrelated, import.sql is plain SQL so you can do what you want, including updating the sequence or table id if needed
Emmanuel Bernard
@Emmanuel Bernard Good to know (+1) I will try it.
Arthur Ronald F D Garcia
+1  A: 

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

Calm Storm
A: 

Like @Calm Storm mentions, try a custom Hibernate sequence generator. Here's some a sample.

Marcus