我有一个带有生成ID的表,但是在某些情况下,我想自行设置它。我可以以某种方式强制Hibernate忽略@GeneratedValue吗?
可能是一个矫kill过正,但您是否考虑过编写自己的CustomIDGenerator,它的子类可能表示hibernate的AutoGenerator,并提供了一些方法,您可以在其中设置要生成的下一个类对象的ID,例如
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 } }
这可能会变得复杂,但至少每个hibernatedoco都有可能