惟愿此间无白头 2020-04-19 22:49 采纳率: 0%
浏览 185

JPA 主键生成策略为 Table 时,初始主键值为什么不是预期的值?

各位大佬帮帮小弟吧。求求了!!!

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ID_GENERATOR")
@TableGenerator(name = "ID_GENERATOR", table = "jpa_id_generators", pkColumnName = "PK_NAME", pkColumnValue = "CUSTOMER_ID", valueColumnName = "PK_VALUE")
public Integer getId() {
    return id;
}

图片说明

Customer customer = new Customer();
customer.setAge(19);
customer.setEmail("tc@qq.com");
customer.setLastName("tc");
customer.setCreatedTime(new Date());
customer.setBirth(new Date());
entityManager.persist(customer);

按理来说,allocationSize 默认为 50,initialValue 默认为 0,不写的话 id 就是从 50 开始。实际上是从 -47 开始。allocationSize 我赋值为 100,id 就从 -97开始,这是怎么回事?
图片说明

这是配置文件:

<persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- 添加持久化类 -->
<class>jpa.helloworld.Customer</class>
    <properties>
        <property name="hibernate.connection.url" value="jdbc:mysql:///jpa?serverTimezone=UTC"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="1024"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
</persistence-unit>
  • 写回答

1条回答 默认 最新

  • 憧憬blog 2023-03-15 01:32
    关注

    根据您提供的代码和配置,主键生成策略为 Table 时,初始主键值为不符合预期的情况是因为在使用 TableGenerator 时出现了数据冲突,导致分配的 ID 不是按顺序递增的。

    解决方法是在 table 属性中指定不同的名字,例如:

    @TableGenerator(name = "ID_GENERATOR", table = "CUSTOMER_TABLE_GENERATOR", ...)
    

    同时,在数据库中创建相应的表 CUSTOMER_TABLE_GENERATOR,并清空该表的数据,以确保初始化的主键值为预期值。若已经有大量数据,可以通过建立新的表并将数据备份到新表中来解决冲突。

    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services