saveorupdate()不起作用,而是执行一个select查询,程序中没有提到这个查询(使用spring+hibernate)

xbp102n0  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(477)

这里是主函数,值已经设置为bean。

  1. package demo.sphbIntegrate;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class App
  5. {
  6. public static void main( String[] args )
  7. {
  8. ApplicationContext context=new ClassPathXmlApplicationContext("sphb.xml");
  9. EmployeeDAO edao=(EmployeeDAO) context.getBean("d");
  10. Employee e=new Employee();
  11. e.setId(1);
  12. e.setName("sourav");
  13. e.setSalary(100000);
  14. edao.saveEmployee(e);
  15. }
  16. }

这是bean类。

  1. package demo.sphbIntegrate;
  2. public class Employee
  3. {
  4. private int id;
  5. private String name;
  6. private int salary;
  7. public int getId() {
  8. return id;
  9. }
  10. public void setId(int id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public int getSalary() {
  20. return salary;
  21. }
  22. public void setSalary(int salary) {
  23. this.salary = salary;
  24. }
  25. }

这是我的刀课。

  1. package demo.sphbIntegrate;
  2. import org.springframework.orm.hibernate5.HibernateTemplate;
  3. public class EmployeeDAO
  4. {
  5. HibernateTemplate template;
  6. public void setTemplate(HibernateTemplate template) {
  7. this.template = template;
  8. }
  9. public void saveEmployee(Employee e)
  10. {
  11. template.saveOrUpdate(e);
  12. }
  13. }

根据代码,必须将记录输入表中。然而,发生了一些奇怪的事情,执行了一个select查询,这在整个程序中没有提到。我不能把我的头围绕着这个异常。ps:我确信,我运行的程序是正确的,所有文件都保存正确,而且整个包中没有编写select查询的代码。
以下是输出:

  1. log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
  2. log4j:WARN Please initialize the log4j system properly.
  3. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
  4. Hibernate: select employee_.ID, employee_.NAME as NAME2_0_, employee_.SALARY as SALARY3_0_ from EMPLOYEE employee_ where employee_.ID=?
qco9c6ql

qco9c6ql1#

在这种情况下没有什么可担心的,因为 saveOrUpdate() 完成保存和更新工作。
它首先检查您传递的id是否存在于表中,原因与您看到的select查询相同。如果你仔细观察你的问题

  1. select employee_.ID, employee_.NAME as NAME2_0_, employee_.SALARY as SALARY3_0_ from EMPLOYEE employee_ where employee_.ID=?

你会看到的 ID 在什么情况下。
如果此查询不返回结果,则只插入新记录,否则将进行更新。

相关问题