Hibernate核心类和接口具体介绍


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


二、hibernate.properties

这个文件是曾经老版本号使用的 类似于hibernate.cfg.xml文件。作用和hibernate.cfg.xml一致.

三、hibernate.cfg.xml 

(1)具体介绍

①该文件主要用于指定各个參数,是hibernate核心文件
②默认放在src文件夹下,也能够放在别的文件夹下。


③指定连接数据库的驱动、username、password、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,username,password,连接池.
④管理 *.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();


注:转载请注明出处。!


原文地址:https://www.cnblogs.com/gavanwanggw/p/6774071.html