Hibernate 中用于自动递增 MySQL 主键的 Java 注释是什么 - @Id

What is the Java annotation in Hibernate used to auto increment a MySQL Primary Key - @Id

在这段代码中,我需要将 id 作为主键,并且它必须递增。
id 需要 getter 和 setter 吗?

@Entity
public class Contact {
@Id
private Integer id;
private String firstName;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

尝试使用@GeneratedValue(strategy = GenerationType.IDENTITY)

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

查看有关 Auto Generated Values

的文档

虽然您可以使用 GenerationType.AUTO,但对于 MySQL 和 Hibernate 5 来说这不是一个好主意,因为它将默认为 TABLE 生成器,这对性能不利。

因此,尽管[它将禁用 JDBC 批量插入][3],您应该使用 IDENTITY:

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

或者您可以使用 native 标识符生成器,​​它在 MySQL 上返回到 IDENTITY:

@Id
@GeneratedValue(
    strategy= GenerationType.AUTO, 
    generator="native"
)
@GenericGenerator(
    name = "native", 
    strategy = "native"
)
private Long id;