我有一个名为Employee的类,正在使用session.merge()方法进行更新。 但是此方法正在执行插入语句,而不是更新语句。请帮忙!
@Autowired
private EntityManagerFactory entityManagerFactory;
public void updateEmployee() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Session session = sessionFactory.openSession();
Employee e = session.get(Employee.class, 3);
e.setName("changed!");
session.close();
Session session1 = sessionFactory.openSession();
Transaction transaction = session1.beginTransaction();
session1.merge(e);
transaction.commit();
session1.close();
}
Employee.class
@Entity
@Table(name = "Employee")
public class Employee implements Serializable {
public Employee(String name) {
super();
this.name = name;
}
public Employee() {
super();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToOne
@JoinColumn(name = "department")
private Department department;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
@Version
private Long version;
@Override
public String toString() {
return "Name :" + name + " Department" + department + "version:" + getVersion();
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
EmployeeController.java
@PutMapping(value = "/updateEmployee")
public void updateEmployee() {
dataServiceImpl.updateEmployee();
}
由于我刚刚点击此API,因此会触发选择查询,而不是更新查询。有人可以解释一下为什么会发生这种情况。
此处提供了完整的代码-https://github.com/iftekharkhan09/SpringAuthSecurity/tree/master/HibernateCaching
我们非常感谢您的帮助!