Hibernate框架简单应用
Posted 陈灿坚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate框架简单应用相关的知识,希望对你有一定的参考价值。
Hibernate的核心组件
在基于MVC设计模式的JAVA WEB应用中,Hibernate可以作为模型层/数据访问层。它通过配置文件(hibernate.properties或hibernate.cfg.xml)和映射文件(***.hbm.xml)把JAVA对象或PO(Persistent Object,持久化对象)映射到数据库中的数据库,然后通过操作PO,对数据表中的数据进行增,删,改,查等操作。
除配置文件,映射文件和持久化类外,Hibernate的核心组件包括以下几部分:
a)Configuration类:用来读取Hibernate配置文件,并生成SessionFactory对象。
b)SessionFactory接口:产生Session实例工厂。
c)Session接口:用来操作PO。它有get(),load(),save(),update()和delete()等方法用来对PO进行加载,保存,更新及删除等操作。它是Hibernate的核心接口。
d)Query接口:用来对PO进行查询操。它可以从Session的createQuery()方法生成。
e)Transaction接口:用来管理Hibernate事务,它主要方法有commit()和rollback(),可以从Session的beginTrancation()方法生成。
Persistent Object
持久化对象可以是普通的Javabeans,惟一特殊的是它们与(仅一个)Session相关联。JavaBeans在Hibernate中存在三种状态:
1.临时状态(transient):当一个JavaBean对象在内存中孤立存在,不与数据库中的数据有任何关联关系时,那么这个JavaBeans对象就称为临时对象(Transient Object)。
2.持久化状态(persistent):当一个JavaBean对象与一个Session相关联时,就变成持久化对象(Persistent Object)
3.脱管状态(detached):在这个Session被关闭的同时,这个对象也会脱离持久化状态,就变成脱管状态(Detached Object),可以被应用程序的任何层自由使用,例如可以做与表示层打交道的数据舆对象(Data Transfer Object)。
Hibernate的运行过程
Hibernate的运行过程如下:
A:应用程序先调用Configration类,该类读取Hibernate的配置文件及映射文件中的信息,并用这些信息生成一个SessionFactpry对象。
B:然后从SessionFactory对象生成一个Session对象,并用Session对象生成Transaction对象;可通过Session对象的get(),load(),save(),update(),delete()和saveOrUpdate()等方法对PO进行加载,保存,更新,删除等操作;在查询的情况下,可通过Session对象生成一个Query对象,然后利用Query对象执行查询操作;如果没有异常,Transaction对象将 提交这些操作结果到数据库中。
Hibernate的运行过程如下图:
Hibernate简单示例:
数据:
(
id int primary key,
userName varchar(30),
userPwd varchar(30),
sex varchar(10),
age int
)
视图层:注册页面register.jsp
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="servlet/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>
设计持久化类TRegister.java
package hibernate.PO;
/**
* 持久化类
*/
public class TRegister implements java.io.Serializable {
// Fields
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;
}
// Property accessors
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 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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/study
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">MySQL5.0</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="show_sql">true</property>
<mapping resource="hibernate/PO/TRegister.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="hibernate.PO.TRegister" table="t_register">
<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" length="30" />
</property>
<property name="userPwd" type="java.lang.String">
<column name="userPwd" length="30" />
</property>
<property name="sex" type="java.lang.String">
<column name="sex" length="10" />
</property>
<property name="age" type="java.lang.Integer">
<column name="age" />
</property>
</class>
</hibernate-mapping>
/**
* hibernate 基础类
* @author fengyan
* date 2007-01-09 02:32
*/
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static
{
try
{
Configuration config = new Configuration().configure("/hibernate/hibernate.cfg.xml");
sessionFactory = config.buildSessionFactory();
}
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();
}
}
/**
* @author fengyan
* date 2007-01-09 02:44
* 设计Hibernate控制类
*/
import hibernate.HibernateUtil;
import hibernate.PO.TRegister;
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.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class RegisterServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html;charset=GBK";
public void init() throws ServletException {
// Put your code here
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public 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();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}