Reputation: 355
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;
}
Upvotes: 8
Views: 8842
Reputation: 153810
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;
Upvotes: 16
Reputation: 59986
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
Upvotes: 4