一、Hibernate开发的基本流程
二、Hibernate开发的环境搭建
1、引入Hibernate核心包以及Hibernate依赖包即可。可以在Hibernate目录下的lib equired目录下找到所需jar包。
2、加入数据库驱动。这里主要是采用Mysql数据库来操作,所以在这里引入MysqL的JDBC驱动。
3、提供核心配置文件hibernate.cfg.xml文件(在src文件夹下即可)。
三、数据库方面的操作
在mysql中新建一个数据库Hibernate5,然后建立如下的一个表来进行测试。
create table T_register
(
id int primary key,
userName varchar(30),
userPwd varchar(30),
sex varchar(10),
age int
)
四、编写POJO类
根据数据表的字段情况,创建如下持久化类,实际上是一个javaBean类
package com.chen; public class TRegister{ //定义基本属性,与数据库中的字段对应。注意都是引用类型 private Integer id; private String userName; private String userPwd; private String sex; private Integer age; // Constructors /** default constructor */ public TRegister() { } /** minimal constructor */ public TRegister(Integer id) { this.id = id; } /** full constructor */ public TRegister(Integer id, String userName, String userPwd, String sex, Integer age) { this.id = id; this.userName = userName; this.userPwd = userPwd; this.sex = sex; this.age = age; } // 定义get set方法 public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return this.userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } }
五、配置相关的xml文件
1、配置hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置连接数据库的基本信息 --> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://192.168.1.148:3306/hibernate5</property> <!-- 配置 hibernate 的基本信息 --> <!-- hibernate 所使用的数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <!-- 执行操作时是否在控制台打印 SQL --> <property name="show_sql">true</property> <!-- 是否对 SQL 进行格式化 --> <property name="format_sql">true</property> <!-- 指定关联的 .hbm.xml 文件 --> <mapping resource="com/chen/TRegister.hbm.xml"/> </session-factory> </hibernate-configuration>
注意:Hibernate4连接MySQL5.X数据库无法自动创建表,解决方法把数据库方言设为
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
2、配置映射文件TRegister.hbm.xml
在持久化类所在的包中建立TRegister.hbm.xml ,可以通过eclipse Hibernate插件来完成
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-3-7 22:14:28 by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping> <class name="com.chen.TRegister" table="TREGISTER"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <!-- 我在MYSQL中并没有设置该字段递增,但在Hibernate中依然可以设置为递增 --> <generator class="increment" /> </id> <property name="userName" type="java.lang.String"> <column name="USERNAME" /> </property> <property name="userPwd" type="java.lang.String"> <column name="USERPWD" /> </property> <property name="sex" type="java.lang.String"> <column name="SEX" /> </property> <property name="age" type="java.lang.Integer"> <column name="AGE" /> </property> </class> </hibernate-mapping>
六、编写事务处理类HibernateUtil.java
package hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { Configuration config = new Configuration().configure(); ServiceRegistry serviceRegistry= new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); } catch(Throwable e) { throw new ExceptionInInitializerError(e); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session s = (Session)session.get(); //Open a new Session,if this Thread has none yet if(s == null || !s.isOpen()) { s = sessionFactory.openSession(); session.set(s); } return s; } public static void closeSession() throws HibernateException { Session s = (Session)session.get(); session.set(null); if(s != null) s.close(); } }
七、编写Servlet控制类RegisterServlet
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import com.chen.TRegister; import hibernate.HibernateUtil; /** * Servlet implementation class RegisterServlet */ @WebServlet("/RegisterServlet") public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String CONTENT_TYPE = "text/html;charset=GBK"; /** * @see HttpServlet#HttpServlet() */ public RegisterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); request.setCharacterEncoding("GBK"); PrintWriter out = response.getWriter(); String userName = request.getParameter("userName"); String userPwd = request.getParameter("userPwd"); String sex = request.getParameter("sex"); int age = Integer.parseInt(request.getParameter("age")); TRegister rg = new TRegister(); rg.setAge(age); rg.setSex(sex); rg.setUserName(userName); rg.setUserPwd(userPwd); Session session = HibernateUtil.currentSession();//生成Session实例 Transaction tx = session.beginTransaction(); try { session.save(rg); //保存持久类对象 tx.commit(); //提交到数据库 session.close(); response.sendRedirect("registerOK.jsp"); } catch(HibernateException e) { e.printStackTrace(); tx.rollback(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
八、编写jsp页面进行测试
1、register.jsp
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <!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=GBK"> <title>Insert title here</title> </head> <body> <form action="RegisterServlet" method="POST"> 用户名:<input type="text" name="userName" /><BR> 密 码:<input type="text" name="userPwd" /><BR> 性 别:<input type="text" name="sex" /><BR> 年 龄:<input type="text" name="age" /><BR> <input type="submit" value="save" /> </form> </body> </html>
2、registerOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> 数据已保存到数据库,请查看....... </body> </html>
九、运行验证
运行register.jsp页面,填写信息,完成后点击save完成保存。查看数据库可以看到数据已保存。