各位大佬帮帮小弟吧。求求了!!!
@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>
根据您提供的代码和配置,主键生成策略为 Table 时,初始主键值为不符合预期的情况是因为在使用 TableGenerator 时出现了数据冲突,导致分配的 ID 不是按顺序递增的。
解决方法是在 table 属性中指定不同的名字,例如:
@TableGenerator(name = "ID_GENERATOR", table = "CUSTOMER_TABLE_GENERATOR", ...)
同时,在数据库中创建相应的表 CUSTOMER_TABLE_GENERATOR,并清空该表的数据,以确保初始化的主键值为预期值。若已经有大量数据,可以通过建立新的表并将数据备份到新表中来解决冲突。