gpt4 book ai didi

java - hibernate 中的 saveOrUpdate() 不起作用,而是执行一个选择查询,该查询在程序中没有提到。 (使用spring+hibernate)

转载 作者:行者123 更新时间:2023-11-29 16:20:45 25 4
gpt4 key购买 nike

这里是main函数,已经给bean设置了值。

package demo.sphbIntegrate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context=new ClassPathXmlApplicationContext("sphb.xml");
EmployeeDAO edao=(EmployeeDAO) context.getBean("d");
Employee e=new Employee();
e.setId(1);
e.setName("sourav");
e.setSalary(100000);
edao.saveEmployee(e);
}
}
这是 Bean 类。
package demo.sphbIntegrate;

public class Employee
{
private int id;
private String name;
private int salary;
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

}

这是我的 DAO 类。

package demo.sphbIntegrate;

import org.springframework.orm.hibernate5.HibernateTemplate;

public class EmployeeDAO
{
HibernateTemplate template;

public void setTemplate(HibernateTemplate template) {
this.template = template;
}

public void saveEmployee(Employee e)
{
template.saveOrUpdate(e);
}
}

根据代码,该记录必须输入到表中。然而,发生了一些奇怪的事情,执行了一个选择查询,这在整个程序中没有提到。我无法理解这种异常现象。PS:我确信,我正在运行正确的程序,所有文件都正确保存,而且整个包中没有编写选择查询的代码。

这是输出:

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

最佳答案

在这种情况下无需担心,因为 saveOrUpdate() 会同时执行保存和更新工作。

它首先检查您传递的 ID 是否存在于表中,原因与您看到选择查询的原因相同。如果您仔细观察您的查询

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

您将在where条件下看到ID

如果此查询没有返回结果,则只会插入新记录,否则会发生更新。

关于java - hibernate 中的 saveOrUpdate() 不起作用,而是执行一个选择查询,该查询在程序中没有提到。 (使用spring+hibernate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54519128/

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