休眠模式应该为每个表使用唯一序列吗

休眠模式应该为每个表使用唯一序列吗

本文介绍了休眠模式应该为每个表使用唯一序列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个实体使用 AUTO 密钥生成策略以及 Hibernate postgres

I have several entities using AUTO key generation strategy with Hibernate and postgres.

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

这将生成 hibernate_sequence

现在,我有一个表,其中包含许多缓存数据(如100k条目)和一些用户表。由于两者都使用策略 AUTO ,它们都从相同的休眠序列中获取密钥。结果,即使我只有10个用户,他们的id也都将由6-7位数字组成,例如 123123

Now I have a table that has lots of cache data (like 100k entries), and some user tables. As both use strategy AUTO, they both get their keys from the same hibernate sequence. As a result, even if I only have 10 users, they will all have an id of 6-7 digits long, like 123123.

我不知道一般而言是否应该为每个表引入自定义序列?还是我不应该在乎id的生成?

I wonder if, in general, one should introduce a custom sequence for each table? Or shouldn't I care about the id generation that much?

推荐答案

我最近为我的项目解决了这个问题。我使用增强型序列生成器(这是序列样式生成器的默认值),并将 prefer_sequence_per_entity 参数设置为 true

I have recently solved this problem for my project. I use the Enhanced sequence generator (which is the default for sequence-style generators) and set the prefer_sequence_per_entity parameter to true.

我的 package-info.java的内容

@GenericGenerator(
    name = "optimized-sequence",
    strategy = "enhanced-sequence",
    parameters = {
        @Parameter(name="prefer_sequence_per_entity", value="true"),
        @Parameter(name="optimizer", value="hilo"),
        @Parameter(name="increment_size", value="50")})
package org.example.model;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

在使用方面,您只需要

@Id @GeneratedValue(generator="optimized-sequence")
public long id;

我更喜欢使用单独的序列,因为偶尔我会放一个表并重新创建它,并且我想要ID从一个开始。

I prefer having separate sequences because occasionally I'll drop a table and recreate it, and I want the ID's starting from one.

这篇关于休眠模式应该为每个表使用唯一序列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:31