I am learning Hibernate
with MySql
data base, while making small project i come up with strange behave of hibernate. I am trying to save one entity (code is below), but entity not getting persist into DB. i am using session.save(e)
method only. It is working if i am using @GeneratedValue(strategy=GenerationType.IDENTITY)
and not if i am using @GeneratedValue(strategy=GenerationType.AUTO)
.
Again if i use session transaction ( begin and commit
) it is working in both case (AUTO and IDENTITY).
Again if i use two different entity one with AUTO and another with IDENTITY it is working.
First Entity
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMP_ID")
private int empId;
@Column(name ="name")
private String name;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Second Entity
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "SUPEMPLOYEE")
public class SupperEmploye {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "EMP_ID")
private int empId;
@Column(name ="name")
private String name;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Code for save entity
Session s= HibernateConfig.getSessionFactory().openSession();
//s.getTransaction().begin(); //working if add
Employee e= new Employee();
e.setName("Employee");
s.save(e);
SupperEmploye se = new SupperEmploye();
se.setName("Super Employee");
s.save(se);
s.close();
//s.getTransaction().commit(); // Working if add
HibernateConfig.getSessionFactory().close();
NOTE: Using hibernate 5, MySQL 8, JAVA 8
please comment if need more info
尝试这个
@GeneratedValue(strategy=GenerationType.IDENTITY)
You should use
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
instead of
@GeneratedValue(strategy = GenerationType.AUTO)
Read below this nice article on this.
https://vladmihalcea.com/why-should-not-use-the-auto-jpa-generationtype-with-mysql-and-hibernate/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.