@Id @GeneratedValue 但设置自己的 ID 值 [英] @Id @GeneratedValue but set own ID value

查看:54
本文介绍了@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 它可能子类说 hibernate 的 AutoGenerator 并公开了几个方法,你可以在其中设置要生成的下一个类对象的 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
}
}

这可能会变得复杂,但至少根据 hibernate doco

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

这篇关于@Id @GeneratedValue 但设置自己的 ID 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆