Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 706
Ashwant Manikoth Avatar asked Aug 27 '17 14:08

Ashwant Manikoth


People also ask

What is @ID annotation in Hibernate?

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.

What is the @ID 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.

What does @ID do in Hibernate?

@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.

What is auto increment primary key in MySQL?

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 ], ... );


1 Answers

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;
like image 165
Vlad Mihalcea Avatar answered Oct 27 '22 09:10

Vlad Mihalcea