8

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
  • 142,745
  • 71
  • 566
  • 911
Ashwant Manikoth
  • 355
  • 3
  • 17

2 Answers2

15

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;
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
4

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140