在基于MVC设计模式的JAVA WEB应用中Hibernate可以作为模型层/数据访问层它通过配置文件(hibernateproperties或hibernatecfgxml)和映射文件(***hbmxml)把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中存在三种状态
临时状态(transient):当一个JavaBean对象在内存中孤立存在不与数据库中的数据有任何关联关系时那么这个JavaBeans对象就称为临时对象(Transient Object)
持久化状态(persistent):当一个JavaBean对象与一个Session相关联时就变成持久化对象(Persistent Object)
脱管状态(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简单示例
数据
create table T_register
(
id int primary key
userName varchar()
userPwd varchar()
sex varchar()
age int
)
视图层注册页面registerjsp
用户名
密 码
性 别
年 龄
设计持久化类TRegisterjava
package hibernatePO;
/**
* 持久化类
*/
public class TRegister implements javaioSerializable {
// 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) {
thisid = id;
}
/** full constructor */
public TRegister(Integer id String userName String userPwd String sex Integer age) {
thisid = id;
thisuserName = userName;
thisuserPwd = userPwd;
thissex = sex;
thisage = age;
}
// Property accessors
public Integer getId() {
return thisid;
}
public void setId(Integer id) {
thisid = id;
}
public String getUserName() {
return thisuserName;
}
public void setUserName(String userName) {
thisuserName = userName;
}
public String getUserPwd() {
return thisuserPwd;
}
public void setUserPwd(String userPwd) {
thisuserPwd = userPwd;
}
public String getSex() {
return thissex;
}
public void setSex(String sex) {
thissex = sex;
}
public Integer getAge() {
return thisage;
}
public void setAge(Integer age) {
thisage = age;
}
}
设计Hibernate配置文件hibernatecfgxml
//Hibernate/Hibernate Configuration DTD //EN
configurationdtd>
root
jdbc:mysql://localhost:/study
orghibernatedialectMySQLDialect
MySQL
root
orggjtmmmysqlDriver
true
设计映射文件TRegisterhbmxml
mappingdtd>
设计hibernate基础类HibernateUtiljava
package hibernate;
/**
* hibernate 基础类
* @author fengyan
* date :
*/
import orghibernateHibernateException;
import orghibernateSession;
import orghibernateSessionFactory;
import orghibernatecfgConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static
{
try
{
Configuration config = new Configuration(nfigure(/hibernate/hibernatecfgxml);
sessionFactory = configbuildSessionFactory();
}
catch(Throwable e)
{
throw new ExceptionInInitializerError(e);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException
{
Session s = (Session)sessionget();
//Open a new Sessionif this Thread has none yet
if(s == null || !sisOpen())
{
s = sessionFactoryopenSession();
sessionset(s);
}
return s;
}
public static void closeSession() throws HibernateException
{
Session s = (Session)sessionget();
sessionset(null);
if(s != null)
sclose();
}
}
设计控制类
package hibernateservlet;
/**
* @author fengyan
* date :
* 设计Hibernate控制类
*/
import hibernateHibernateUtil;
import hibernatePOTRegister;
import javaioIOException;
import javaioPrintWriter;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orghibernateHibernateException;
import orghibernateSession;
import orghibernateTransaction;
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() {
superdestroy(); // Just puts destroy string in log
// Put your code here
}
public void doGet(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
responsesetContentType(CONTENT_TYPE);
requestsetCharacterEncoding(GBK);
PrintWriter out = responsegetWriter();
String userName = requestgetParameter(userName);
String userPwd = requestgetParameter(userPwd);
String sex = requestgetParameter(sex);
int age = IntegerparseInt(requestgetParameter(age));
TRegister rg = new TRegister();
rgsetAge(age);
rgsetSex(sex);
rgsetUserName(userName);
rgsetUserPwd(userPwd);
Session session = HibernateUtilcurrentSession();//生成Session实例
Transaction tx = sessionbeginTransaction();
try
{
sessionsave(rg); //保存持久类对象
mit(); //提交到数据库
sessionclose();
responsesendRedirect(registerOKjsp);
}
catch(HibernateException e)
{
eprintStackTrace();
txrollback();
}
}
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
doGet(requestresponse);
}
}