gpt4 book ai didi

java - Hibernate saveOrUpdate 不会更新现有记录,而是将记录另存为新条目

转载 作者:行者123 更新时间:2023-11-29 19:42:03 26 4
gpt4 key购买 nike

从今天早上开始就一直在寻找这个问题,但我找不到这个问题的正确答案,我正在使用 ID 作为引用来更新记录,但不是更新应用程序而是插入现有的新条目记录,控制台显示“插入”而不是“更新”。以下是该应用程序的片段:

Controller :

@PostMapping("/saveCustomer")
public String saveCustomer(@ModelAttribute("customer") Customer customer) {

customerService.saveCustomer(customer);

return "redirect:/erp/list";
}

@GetMapping("/showFormForUpdate")
public String showFormForUpdate(@RequestParam("customerId") int id, Model model) {

Customer customer = customerService.getCustomer(id);

model.addAttribute("customer", customer);

return "customer-form";
}

DAO 实现:

@Override
public void saveCustomer(Customer customer) {
Session currentSession = sessionFactory.getCurrentSession();

currentSession.saveOrUpdate(customer);
}

实体:

@Entity
@Table(name="customer")
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="company_name")
private String companyName;

@Column(name="company_email")
private String companyEmail;

@Column(name="company_address")
private String companyAddress;

@Column(name="contact_no")
private String contactNo;

@Column(name="company_tin")
private String companyTin;

public Customer() {

}

public String getContactNo() {
return contactNo;
}

public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}

public String getCompanyName() {
return companyName;
}

public void setCompanyName(String companyName) {
this.companyName = companyName;
}

public String getCompanyEmail() {
return companyEmail;
}

public void setCompanyEmail(String companyEmail) {
this.companyEmail = companyEmail;
}

public String getCompanyAddress() {
return companyAddress;
}

public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}

public String getCompanyTin() {
return companyTin;
}

public void setCompanyTin(String companyTin) {
this.companyTin = companyTin;
}

public int getId() {
return id;
}

最佳答案

我认为您的 bean 中缺少 setter 方法:

public int setId(int id) {
this.id = id;
}

这就是为什么当您添加模型属性时,它不会在您的 bean 中设置 id 值。

关于java - Hibernate saveOrUpdate 不会更新现有记录,而是将记录另存为新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com