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

标签 java hibernate hql

这是执行插入操作的 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/

相关文章:

java - HQL查询where存在或列表元素之间

java - hibernate 无法与 Heroku postgresql 插件连接

java - 无法在 Ubuntu 16.04 LTS 上从 Eclipse Neon 打开 Eclipse Marketplace

java - 使用 Jsoup.Jar 进行 HTML 解析

java - 是否可以在 JAVA 中以非字母顺序返回 SOAP 消息?

java - 为什么在调用 setVisible(false) 和 dispose() 时调用的窗口/组件监听器不同?

java - 使用注释的 hibernate 映射

java - 在 WHERE 子句中使用多对多集(连接表)进行查询

java - hibernate 条件 : find entity if any of its children's children have a specific property

java - 表名引起的 SQLGrammarException 错误