[英]Manually set auto generated id property
In Hibernate is there a way to skip generating the value of a @GeneratedValue
property by manually setting it before calling save
on the session? 在Hibernate中,有没有一种方法可以通过在会话上调用save
之前手动设置它来跳过生成@GeneratedValue
属性的值的方法?
I am building an import/export facility and I would like to preserve the IDs from a previously made export. 我正在建立一个进出口设施,我想保留以前出口的证件。
Is important to say, if you use this way: 重要的是要说,如果使用这种方式:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
And you don't have the id you set in the database it will ignore your id set and the database will create a new one. 而且您没有在数据库中设置的ID,它将忽略您的ID设置,数据库将创建一个新ID。 I mean, if you have an empty database and set user.setId(100L)
and save, when you find it in database the service.findById(100L)
will not find any object. 我的意思是,如果您有一个空数据库并设置user.setId(100L)
并保存,则当您在数据库中找到它时, service.findById(100L)
将找不到任何对象。
By default, Hibernate won't override value if it was already set, so everything should work as you expect. 默认情况下,Hibernate不会覆盖已设置的值,因此一切都会按您期望的那样进行。 Just make sure you're not using AUTO. 只要确保您没有使用AUTO。
If you need a more complex logic, take a look at @GenericGenerator. 如果您需要更复杂的逻辑,请查看@GenericGenerator。 https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-identifier https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-identifier
@GeneratedValue
will only apply it's strategy if the id
on which you're applying this annotation is null
/ 0
. @GeneratedValue
仅在要应用此批注的id
为null
/ 0
才应用其策略。
This means that if you've manually assigned an id
field, then @GeneratedValue
annotation is USELESS. 这意味着,如果您手动分配了id
字段,则@GeneratedValue
注释为USELESS。
The problem is that I was using the default ( AUTO
) strategy for the @GeneratedValue
. 问题是我对@GeneratedValue
使用默认( AUTO
)策略。 If I change it to explicitly specify IDENTITY
then it works! 如果我将其更改为显式指定IDENTITY
那么它将起作用!
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
I don't really understand why though... :-) 我真的不明白为什么... :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.