Hibernate连数据库
1.建数据库,建表(一定要设主码)
create database Hibernate create table Students( sno char(10) primary key, sna char(10), )
2.打开Myeclipse,建web项目,一定要选java EE6.0
3.先将jar包拷到lib下:
4.用DB Browser连数据库:右击-New,弹出如下对话框:
这样选择:注意Driver JARs添加刚刚拷的jar包
然后点Test Driver出现如下图表示成功连到数据库
然后Next,选第三个Display the selected schemas,然后ADD
然后选择刚建的数据库Hibernate:
然后Finish。
5.右击项目名Hibernate-Myeclipse-Add Hibernate Capabilities,按如图这样选择,然后下一步
下一步,DB Driver选择Hibernate
下一步,建包,完成
这样就添加了HibernateSessionFactory.java和hibernate.cfg.xml
6.回到DB Browser,右击Hibernate-Open connection,打开链接。然后找到自己的表Students
右击表名Students-Hibernate Reverse Engineering,在Java src folder中选Hibernate
下一步
下一步
完成,这是在项目中又添加了Students.java和Students.hbm.xml
7.编代码实现简单的插入
建StudentAdd.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form id="form1" action="servlet/StudentAdd" method="post"> 学号<input type="text" id="id" name="id"> 姓名<input type="text" id="name" name="name"> <input type="submit" value="提交"> </form> </body> </html>
建servelet:StudentAdd.java:
package com.aa.orm; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; public class StudentAdd extends HttpServlet { /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String strid=""; String strname=""; strid=request.getParameter("id"); strname=request.getParameter("name"); Session ss = HibernateSessionFactory.getSession(); ss.beginTransaction(); Students s = new Students(); s.setSno(strid); s.setSna(strname); ss.save(s); System.out.println(strid); ss.getTransaction().commit(); ss.close(); response.sendRedirect("../index.jsp"); } }
结果:
表示插入成功。