本文介绍了@Id @GeneratedValue但设置了自己的ID值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有生成ID的表格,但在某些情况下,我想自行设置它。我可以,不知何故,迫使Hibernate忽略@GeneratedValue?
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?
推荐答案
这可能是一个矫枉过正,但你有没有想过写你的自己的CustomIDGenerator,它可能是子类,说AutoGenerator的hibernate,并公开了一些方法,你可以设置下一个类的对象的ID,例如生成所以例如
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
这篇关于@Id @GeneratedValue但设置了自己的ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!