[英]@GeneratedValue(strategy = GenerationType.AUTO): MySQL and generated IDs shared between tables?
I have some tables in MySQL database.我在 MySQL 数据库中有一些表。 I am implementing a Spring Boot application and now testing the database.我正在实现 Spring 引导应用程序,现在正在测试数据库。 I have @Entities:我有@Entity:
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
...
public class Publisher implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
My issue is the following: When I save the above in the MySQL database, the generated IDs in the databases are "shared".我的问题如下:当我将上述内容保存在 MySQL 数据库中时,数据库中生成的 ID 是“共享的”。 By that, I mean that for example, first the Publisher table gets the ID 1, and the Author gets ID 2 and 3. Then, in the next run, Publisher gets ID 4, and Author 5 and 6. And so on.我的意思是,例如,首先 Publisher 表获得 ID 1,Author 获得 ID 2 和 3。然后,在下一次运行中,Publisher 获得 ID 4,Author 5 和 6。依此类推。 What I would like is this: That Publisher table gets IDs 1 2 3..., and Authors get IDs 1 2 3... Is this possible?我想要的是:Publisher 表的 ID 为 1 2 3...,而 Authors 的 ID 为 1 2 3... 这可能吗? I am using MySQL database and Spring Boot with JPA dependencies.我正在使用 MySQL 数据库和 Spring 启动与 JPA 依赖项。
That happens because on any database that does not support sequences natively, such as MySQL, hibernate is using the TABLE generator instead of IDENTITY, when generation type is set to AUTO.发生这种情况是因为在任何不支持本机序列的数据库(例如 MySQL、hibernate)上,当生成类型设置为 AUTO 时,使用的是 TABLE 生成器而不是 IDENTITY。 You can check that a table with sequences of ids is generated by hibernate that will tell which id is the next one to be used (hibernate_sequence).您可以检查 hibernate 是否生成了带有 id 序列的表,该表将告知下一个要使用的 id (hibernate_sequence)。
You are looking for the IDENTITY generator:您正在寻找 IDENTITY 生成器:
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
...
public class Publisher implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
More info:更多信息:
https://www.baeldung.com/hibernate-identifiers#2-identity-generation https://www.baeldung.com/hibernate-identifiers#2-identity-generation
https://hibernate.atlassian.net/browse/HHH-11014 https://hibernate.atlassian.net/browse/HHH-11014
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.