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;
}
The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation.
The @Id annotation offer the simplest mechanism to define the mapping to the primary key. You can associate the @Id annotation to fields/properties of these types: Primitive Java™ types and their wrapper classes. Arrays of primitive or wrapper types. Strings: java.
@Id will only declare the primary key. it will not insert generated value. if you use @GeneratedValue then it will generate the value of the field.
You can set the MySQL Auto Increment Primary Key field via the following syntax: CREATE TABLE table_name ( column1 datatype NOT NULL AUTO_INCREMENT, column2 datatype [ NULL | NOT NULL ], ... );
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With