Hibernate核心类和接口详细介绍

来源:互联网 发布:淘宝手机海报尺寸 编辑:程序博客网 时间:2024/04/30 14:20


一、hiobernate核心类和接口预览图


二、hibernate.properties

这个文件是以前老版本使用的 类似于hibernate.cfg.xml文件;作用和hibernate.cfg.xml一致.

三、hibernate.cfg.xml 

(1)详细介绍

①该文件主要用于指定各个参数,是hibernate核心文件
②默认放在src目录下,也可以放在别的目录下。
③指定连接数据库的驱动、用户名、密码、url、连接池..
④指定对象关系映射文件的位置.
⑤也可使用hibernate.properties文件来替代该文件.(推荐使用hibernate.cfg.xml)。

(2)配置文件模板

<?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的核心配置文件 --><hibernate-configuration><session-factory><!--配置使用的driver  --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.username">root</property><property name="connection.password">xu827928</property><property name="connection.url">jdbc:mysql://127.0.0.1:3306/hbmtest</property><!-- 配置dialect方言,明确告诉hibernate连接的是哪种数据库 --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- 显示出对应sql语句 --><property name="show_sql">true</property><!-- 格式化输出sql语句 --><property name="format_sql">true</property><!--让hibernate帮我们创建 一张表 --><!-- update:如果没有表则创建表 如果有表 则看表结构是否变化 如果有变化则会创建新表如果没有则添加create:每次都创建新的数据库 --><!-- <property name="hbm2ddl.auto">create</property> --><property name="hbm2ddl.auto">update</property><!-- 指定管理对象映射文件 --><mapping resource="com/lc/domain/Employee.hbm.xml"></mapping></session-factory></hibernate-configuration>

四、*.hbm.xml

(1)对象关系映射文件(*.hbm.xml)

  ①该文件主要作用是建立表和类的映射关系,是不可或缺的重要文件.
  ②一般放在其映射的类同一个目录下,但不是必须的。
  ③命名方式一般是 类名.hbm.xml,但不是必须的。

④示意图:


(2)配置文件模板

<?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'><!-- 这是映射Employee表的hibernate --><!-- 该文件用于配置domain对象和表的映射关系 --><hibernate-mapping package="com.lc.domain"><class name="Employee" table="employee"><!-- id元素用于指定主键属性 --><id name="id" column="id" type="java.lang.Integer"><generator class="increment" /> </id><!-- 对其他属性的配置 --><property name="name" type="java.lang.String"><column name="name" not-null="false" /></property><property name="email" type="java.lang.String"><column name="email" not-null="false" /></property><property name="hiredate" type="java.util.Date"><column name="hiredate" not-null="false" /></property></class></hibernate-mapping>

五、Configuration类

(1)详细介绍

①负责管理hibernate的配置信息
②读取hibernate.cfg.xml
③加载hibernate.cfg.xml配置文件中配置的驱动,url,用户名,密码,连接池.
④管理 *.hbm.xml对象关系文件.

(2)示意代码:

Configuration cf=new Configuration().configure();

六、SessionFactory(会话工厂)接口

(1)详细介绍

①缓存sql语句和某些数据

②在应用程序初始化的时候创建,是一个重量级的类(吃内存),一般用单例模式保证一个应用中只需要一个 SessionFactory实例.

③如果某个应用访问多个数据库,则要创建多个会话工厂实例,一般是一个数据库一个会话工厂实例.
④通过SessionFactory接口可以获得Session(会话)实例.

(2)示意代码:

 Configuration cf=new Configuration().configure();  SessionFactory sf=cf.buildSessionFactory();  Session s=sf.getCurrentSession();  //或者是: Session s=sf.openSession();

七、Session(会话)接口

(1)接口介绍

 ①Session一个实例代表与数据库的一次操作(当然一次操作可以是crud组合)

  ②Session实例通过SessionFactory获取,用完需要关闭。
  ③Session是线程不同步的(不安全),因此要保证在同一线程中使用,可以用getCurrentSessiong()。
  ④Session可以看做是持久化管理器,它是与持久化操作相关的接口

(2)示意代码:

Configuration cf=new Configuration().configure();SessionFactory sf=cf.buildSessionFactory();Session s=sf.getCurrentSession();//或者是: Session s=sf.openSession();

(3)Session(会话)接口的几个重要方法

Session一般以对象的形式来操作,这里
给大家演示一下吧!(请参考文档)
①保存一个对象(记录)—save方法
②删除一个对象(记录)—delete方法
③查询一个对象(记录)—get/load方法
④修改一个对象(记录)—update方法

(4)get()和load()区别

1、get()方法直接返回实体类,如果查不到数据则返回null。load()会
返回一个实体代理对象(当前这个对象可以自动转化为实体对象),
但当代理对象被调用时,如果没有数据不存在,就会抛出个
org.hibernate.ObjectNotFoundException异常


2.load先到缓存(session缓存/二级缓存)中去查,如果没有则返回一个
代理对象(不马上到DB中去找),等后面使用这个代理对象操作的时
候,才到DB中查询,这就是我们常说的 load在默认情况下支持延迟加
载(lazy)


3. get先到缓存(session缓存/二级缓存)中去查,如果没有就到DB中去
查(即马上发出sql)。总之,如果你确定DB中有这个对象就用
load(),不确定就用get()(这样效率高)

load VS get

1. 如果查询不到数据,get 会返回 null,但是不会报错, load 如果查询不到数据,则报错ObjectNotFoundException

2. 使用get 去查询数据,(先到一级/二级)会立即向db发出查询请求(select ...), 如果你使用的是 load查询数据,(先到一级、二级))即使查询到对象,返回的是一个代理对象,如果后面没有使用查询结果,它不会真的向数据库发select ,当程序员使用查询结果的时候才真的发出select ,这个现象我们称为懒加载(lazy)

3. 通过修改配置文件(*.hbm.xml文件),我们可以取消懒加载

<class  name="Employee" lazy="false" table="employee">

4. 如何选择使用哪个如果你确定DB中有这个对象就用load(),不确定就用get()(这样效率高)

(5)openSession()和 getCurrentSession()区别

①采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()创建的session则不会

②采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()创建的session必须手动关闭.
③使用getCurrentSession()需要在hibernate.cfg.xml文件中加入

如下配置:
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property> 

(6) openSession()和 getCurrentSession()联系

深入探讨:
在 SessionFactory启动的时候,Hibernate 会根据配置创建相应的 CurrentSessionContext,在getCurrentSession()被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession()。

在currentSession()执行时,如果当前Session为空,currentSession会调用SessionFactory的openSession。

(7)openSession()和 getCurrentSession()究竟选谁?

原则:
①如果需要在同一线程中,保证使用同一个Session则,使用getCurrentSession()
②如果在一个线程中,需要使用不同的Session,则使用opentSession()

(8)openSession()和 getCurrentSession()联系,用ThreadLocal模式 (线程局部变量模式) 管理Session,代码如下:

public class HibernateUtil {public static final ThreadLocal session =new ThreadLocal();public static final SessionFactory sessionFactory;   static {      try {        sessionFactory = new Configuration().configure().buildSessionFactory();      } catch (Throwable ex) {           throw new ExceptionInInitializerError(ex);      }     }  public static Session currentSession() throws HibernateException {        Session s = session.get();        if(s == null) {          s = sessionFactory.openSession();session.set(s);}         return s;}     public static void closeSession() throws HibernateException {           Session s = session.get();        if(s != null) { s.close();}        session.set(null); }}



八、Transaction(事务)接口

(1)这里我们简单给大家说明一下什么是事务。

事务简单的说,就是一组对数据库的操作集合,它们要么全部成功,要么全部失败.这个可以保证数据的一致性,事务具有原子性。
①Transaction是底层的事物实现中抽象出来的接口
②可能是一个jdbc或者jta的事务,这样有利于hibernate在不同执行环境的移植。
③hibernate要求显示的调用事务(如果仅仅是查询可以不调用.)

Transaction ts=s.beginTransaction();
...
ts.commit();s.close(); 发生异常需要ts.rollback()回滚.

(2)全局事务和本地事务

本地事务:针对一个数据库的事务;(jabc事务)
全部事务:跨数据库的事务(jta事务);

如果要使用getCurrentSession的时候就需要在hibernate.cfg.xml文件中根据实际配置
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property> 

九、Query接口

(1)Query接口类型的对象可以对数据库操作,它可以使用Hql,Qbc,Qbe和原生SQL(native Sql)对数据库操作.官方推荐使用Hql语句。

十、 Criteria接口

Criteria接口也可用于面向对象方式的查询,关于它的具体用法我们
这里先不做介绍,简单看几个案例.
最简单案例:返回50条记录

Criteria crit = sess.createCriteria(Cat.class);crit.setMaxResults(50);List cats = crit.list();
限制结果集内容
List cats = sess.createCriteria(Cat.class)  .add( Restrictions.like("name", "Fritz%") )  .add( Restrictions.between("weight", minWeight, maxWeight) )  .list();


注:转载请注明出处!!


5 0
原创粉丝点击