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

Ashwant Manikoth :

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;
}
Vlad Mihalcea :

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

So, although it will disable JDBC batch inserts, 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;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464165&siteId=1