在 Hibernate 中绕过 GeneratedValue [英] Bypass GeneratedValue in Hibernate

查看:22
本文介绍了在 Hibernate 中绕过 GeneratedValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Hibernate 中为 ID 绕过 @GeneratedValue,我们有一种情况,大多数时候我们希望使用 GeneratedValue 设置 ID,但在某些情况下需要手动设置 ID.

Is it possible to bypass @GeneratedValue for an ID in Hibernate, we have a case where, most of the time we want the ID to be set using GeneratedValue, but in certain cases would like to set the ID manually.

这可以吗?

推荐答案

我知道您可以在 JPA 规范中执行此操作,因此您应该可以在 Hibernate 中执行此操作(使用 JPA+ 注释).

I know you can do this in the JPA spec, so you should be able to in Hibernate (using JPA+ annotations).

如果您只是填写您正在创建的新持久模型的 ID 字段,那么当您将该模型合并"到 EntityManager 中时,它将使用您设置的 ID.

If you just fill in the ID field of the new persistent model you're creating, then when you "Merge" that model into the EntityManager, it will use the ID you've set.

不过,这确实有影响.您刚刚用完该 ID,但 GeneratedValue 注释指定的序列不知道这一点.除非您指定一个小于当前序列值的未使用 ID,否则一旦序列赶上您刚刚使用的值,您就会遇到问题.

This does have ramifications, though. You've just used up that ID, but the sequence specified by the GeneratedValue annotation doesn't know that. Unless you're specifying an ununsed ID that's LESS than the current sequence value, you're going to get a problem once the sequence catches up to the value you just used.

所以,也许我可以看到您可能希望用户能够指定 ID 的位置,但是您需要捕获将来可能出现的异常(重复 ID).

So, maybe I can see where you might want the user to be able to specify an ID, but then you need to catch the possible Exception (duplicate ID) that may come in the future.

这篇关于在 Hibernate 中绕过 GeneratedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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