简体   繁体   中英

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

In this code I need the id to be the primary key and also it must be incremented.
is getter and setter required for id ?

@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;
}

Although you could use GenerationType.AUTO , it's not a very good idea for MySQL and Hibernate 5 because it will default to the TABLE generator which is bad for performance.

So, although [it will disable JDBC batch inserts][3], you should use IDENTITY :

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

or you can use native identifier generator which falls back to IDENTITY on MySQL:

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

try to use @GeneratedValue(strategy = GenerationType.IDENTITY)

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

take a look in this doc about Auto Generated Values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM