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

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

问题描述

是否有可能为Hibernate中的ID绕过 @GeneratedValue ,我们有一种情况,大多数时候我们希望使用<$ c设置ID $ c> GeneratedValue ,但在某些情况下想手动设置ID。



这可能吗?

解决方案

我知道你可以在JPA规范中做到这一点,所以你应该可以在Hibernate中使用JPA +注解。 b
$ b

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

尽管如此,这确实有分歧。您刚用完该ID,但由GeneratedValue注释指定的序列不知道。除非您指定的未使用ID比当前序列值少,否则一旦顺序达到您刚刚使用的值,您将遇到问题。



因此,也许我可以看到你可能希望用户能够指定一个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.

Is this possible to do?

解决方案

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

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.

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.

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天全站免登陆