使用 Hibernate 在 Java 中实现序列
我使用 Java 和 Hibernate 作为 ORM 工具。有什么方法可以使用 Hibernate 在 Java 中实现序列吗?
目前我正在使用 Oracle 序列来实现此目的,但随着与数据库交互的增加,这是一种非常昂贵的方法。
I am using Java and Hibernate as ORM tool. Is there any way i can implement sequence in Java using Hibernate?
Currently I am using Oracle sequences to achieve this, but that is a very costly way as interaction with database increases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这实际上是一件非常简单的事情:
IdentitfierGenerator 是您必须实现的 hibernate 接口。上面的例子只是生成一个随机id。
为了使用它,你必须将
generator
设置为mypackage.RandomIdentifierGenerator
显然,这个实现缺乏任何不生成相同 id 两次的保证,这可能很重要,也可能不重要对于您正在编写的应用程序。
It is actually a very easy thing to do:
IdentitfierGenerator
is the hibernate interface you have to implement. The above example just generates a random id.In order to use this you have to set the
generator
tomypackage.RandomIdentifierGenerator
Obviously this implementation lacks any guarantee of not generating the same id twice, this may or may not be important for the application you are writing.
您确定使用 Oracle 序列的成本很高吗?正如其他评论者所提到的,这不太可能。话虽如此,您应该尝试使用增量超过 1 的序列。将此类序列与
hi-lo
或pooled
一起使用 优化器,可能效果很好。如果N
是序列的增量大小,这可确保 HibernateSession
在N
插入中仅访问数据库一次。缺点是您必须使用单独的create_time
列来标识行的插入顺序。Are you sure that using Oracle sequences is costly? As other commenters have mentioned, this is unlikely. Having said that, you should try to use sequences that increment by more than 1. Using such sequences along with
hi-lo
orpooled
optimizers, is likely to work well. This ensures that a HibernateSession
will hit the database only once inN
inserts, ifN
is the increment size of the sequence. The downside is that you will have to use a separatecreate_time
column to identify the order of insertion of rows.我用这个来生成主键:java.util.UUID.randomUUID().toString().replaceAll("-", "");
它将生成32位主键,如下所示:1b694a70285f49c8a25a5de598042e7b 。
使用这种方法几乎没有机会获得重复的主键。
最好将其与 hibernateGenerateValue 一起使用。
示例代码如下:
uuid 设置策略是由 Hibernate 提供的,您可以通过使用自己的类的限定名设置策略来使用自己的 Java 类。
I use this to generate primary key :java.util.UUID.randomUUID().toString().replaceAll("-", "");
It will generate 32-digit primary key like this:1b694a70285f49c8a25a5de598042e7b .
It has little chance to get duplicate primary key by using this approach.
It would be nice to use this with hibernate GeneratedValue.
sample code would like be :
uuid set by to strategy is provided by Hibernate, you can feel like to use your own Java class by set strategy using qualified name of your own class.