我有一个简单的pojo员工:
@Entity
@Table(name = "employee")
public class Employee {
@Id@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "emp_sequence")
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
public Employee() {
/*
Just a no-arg constructor for an Entity
*/
}
public Employee(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Employee: " + this.id + ", " + this.name + ", " + this.age;
}
}
当我尝试使用session.save(e)将Employee保存在数据库中时; 所有对象都使用错误的ID进行更新
将员工添加到数据库的代码:
public static void main(String[] args) {
Employee em1 = new Employee("Mary Smith", 25);
Employee em2 = new Employee("John Aces", 32);
Employee em3 = new Employee("Ian Young", 29);
System.out.println(" =======CREATE =======");
create(em1);
create(em2);
create(em3);
System.out.println(" =======READ =======");
List<Employee> ems1 = read();
for(Employee e: ems1) {
System.out.println(e.toString());
}
public static Integer create(Employee e) {
Session session = getSessionFactory().openSession();
session.beginTransaction();
session.save(e);
session.getTransaction().commit();
session.close();
System.out.println("Successfully created " + e.toString());
return e.getId();
}
public static List<Employee> read() {
Session session = getSessionFactory().openSession();
@SuppressWarnings("unchecked")
List<Employee> employees = session.createQuery("FROM Employee").list();
session.close();
System.out.println("Found " + employees.size() + " Employees");
return employees;
}
}
SQL日志:
=======CREATE =======
Hibernate: select emp_sequence.nextval from dual
Hibernate: insert into employee (age, name, id) values (?, ?, ?)
Successfully created Employee: 200, Mary Smith, 25
Hibernate: insert into employee (age, name, id) values (?, ?, ?)
Successfully created Employee: 201, John Aces, 32
Hibernate: insert into employee (age, name, id) values (?, ?, ?)
Successfully created Employee: 202, Ian Young, 29
=======READ =======
Hibernate: select employee0_.id as id1_0_, employee0_.age as age2_0_, employee0_.name as name3_0_ from employee employee0_
Found 3 Employees
Employee: 7, Ian Young, 29
Employee: 5, Mary Smith, 25
Employee: 6, John Aces, 32
从日志中可以看出,持久化实体中更新的员工ID为200,201和202 来自DB的实际ID是7,8和9