gpt4 book ai didi

java - HQL的插入子句不更新数据库

转载 作者:行者123 更新时间:2023-12-01 12:56:30 26 4
gpt4 key购买 nike

这是执行插入操作的 servlet:

InsertClause.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HibInsert</title>");
out.println("</head>");
out.println("<body>");

Configuration cfg= new Configuration();
cfg= cfg.configure("hibernate.cfg.xml");
SessionFactory sf= cfg.buildSessionFactory();
Session ses=sf.openSession();
Transaction tx= ses.beginTransaction();
out.println("execution...");

Query q= ses.createQuery("insert into Student(id,age) select ns.id,ns.age from NewStudent ns where ns.id=109");

int res= q.executeUpdate();
out.println("transfer successfull !!<br/>");
out.println("number of records transferred: "+res);

out.println("</body>");
out.println("</html>");
}
}

应用程序中使用的其他文件是:

1.Student.java(POJO)

2.NewStudent.java(POJO)

3.student.hbm.xml

4.newstudent.hbm.xml

5.hibernate.cfg.xml

数据库中使用的两个表:newstudent 和 mystudent

浏览器上的输出正在获取:

转账成功!!

传输的记录数:1

但是在数据库中,当我打开 mystudent 表时,记录未插入!那么可能出了什么问题呢?

最佳答案

您需要在 executeUpdate() 方法之后提交事务。

Transaction tx= ses.beginTransaction();
out.println("execution...");

Query q= ses.createQuery("insert into Student(id,age) select ns.id,ns.age
from NewStudent ns where ns.id=109");

int res= q.executeUpdate();
tx.commit(); // Add this line.

关于java - HQL的插入子句不更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23841326/

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