这是执行插入操作的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表时数据库中没有插入记录!那可能出了什么问题?
答案 0 :(得分:1)
您需要在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.