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
2010-01-21 14:21:20
It is not an answer.
Arthur Ronald F D Garcia
2010-01-21 16:05:32
on startup I want to set a 'no User' with id 0
woezelmann
2010-01-22 09:58:11
+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
2010-01-24 18:21:52
@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
2010-02-05 03:44:39
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
2010-02-19 13:55:16
+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
2010-02-15 10:59:50