熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

淺談Hibernate框架簡述

2022-06-13   來源: Java開源技術 

  在基於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);

  }

  }


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28144.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.