6月19日,小雨。“黄梅时节家家雨。青草池塘处处蛙。有约不来过夜半,闲敲棋子落灯花。”

面向对象无限包容的个性,给对SQL和数据库一窍不通的澳大利亚人Gavin King创造了极大的想象空间。那些原本尴尬的不利因素---OO对象模型和关系型数据库之间的设计理念上的差异即-“O/R阻抗失衡(O/R Impedance
Mismatch)”等。

在澳大利亚人的转化手段中,都被自觉或不自觉地消除了。

Hibernate的出现,让面向对象的对象模型和关系型数据库的数据结构之间的相互转换达到了一种高峰。

好的coder对Hibernate的Session的理解往往会让人大吃一惊。

也许能够说,澳大利亚人用Session表达了自己柔软变通的适应性。

全部的这些。让每个Session在open和close之间的短暂生命得到了升华。

Session接口负责运行被持久化对象的CRUD操作(CRUD的任务是完毕与数据库的交流。包括了非常多常见的SQL语句。)。但须要注意的是Session对象是非线程安全的。

1、自己动手。封装HibernateUtil类

在运用中为避免资源消耗,一般都会手动封装一个HibernateUtil类(未使用Spring管理的前提下)。该类的作用使Hibernate载入配置文件config, 创建sessionFactory等仅仅执行一次。

package edu.eurasia.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration; /**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution.
*/
public class HibernateUtil { /**
* Location of hibernate.cfg.xml file. NOTICE: Location should be on the
* classpath as Hibernate uses #resourceAsStream style lookup for its
* configuration file. That is place the config file in a Java package - the
* default location is the default Java package.<br>
* <br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; /** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal(); /** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration(); /** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory; /**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* Default constructor.
*/
private HibernateUtil() {
}
}

2、 Hibernate使用事务

Hibernate对JDBC进行了轻量级的封装,它本身在设计时并不具备事务处理功能。Hibernate将底层的JDBCTransaction或JTATransaction进行了封装,再在外面套上Transaction和Session的外壳,事实上是通过托付底层的JDBC或JTA来实现事务的处理功能的。

package edu.eurasia.hibernate;

import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.Transaction; public class SimpleTransaction {
public static void main(String[] args) {
SimpleTransaction simpleTran = new SimpleTransaction();
simpleTran.tran();
} // 演示事务使用的方法
public void tran() {
// 得到当前事务
Session session = HibernateUtil.currentSession();
// 声明事务
Transaction tx = null;
try {
// HQL查询语句
String hql = "from UserInfo";
// 事务的開始
tx = session.beginTransaction();
// 事务的中间操作
Iterator it = session.createQuery(hql).list().iterator();
while (it.hasNext()) {
UserInfo userinfo = (UserInfo) it.next();
System.out.println(userinfo.getUsername()+" "+userinfo.getPassword());
}
// 提交事务
tx.commit();
} catch (Exception ex) {
if (tx != null) {
try {
// 回滚事务
tx.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
// 关闭session
session.close();
}
}
}

3、MySQL数据库。UserInfo类,映射文件UserInfo.hbm.xml和hibernate.cfg.xml配置文件见:

第十九天 慵懒的投射在JDBC上的暖阳 —Hibernate的使用(一)

4、还须要加入一个slf4j-nop-1.6.2.jar文件。

project结构例如以下:

实际运用中,常常须要将当前线程和session绑定.一般的使用方法为使用ThreadLocal: 在HibernateUtil类中封装hibernate的管理.通过openSession取得session,并将其放入ThreadLocal变量中.
这样业务逻辑中仅需通过工具类取得当前线程相应的session.使用完成后,调用工具类closeSession方法将session关闭,当前线程的ThreadLocal变量置为NULL. 保证线程归还线程池复用后,ThreadLocal为空,以免出现导致其他线程訪问到本线程变量。

而后,Hibernate的SessionFactory提供获取session的新方法getCurrentSession (获得与当前线程绑定的session). 内部通过代理封装,此方式得到的session不仅和当前线程绑定,也无需手动开关.
默认在事务提交之后,session自己主动关闭。

末了,引入Spring之后.sessionfactory的创建等都交给spring管理.Spring也提供了HibernateTemplate。 HibernateDaoSupport这种封装方法。

用户能够不再考虑session的管理,事务的开启关闭.仅仅需配置事务就可以。

第三十一天 慵懒的投射在JDBC上的暖阳 —Hibernate的使用(四)的更多相关文章

  1. 第二十五天 慵懒的投射在JDBC上的暖阳 —Hibernate的使用(四)

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/zwszws/article/details/28493209            6月4日.晴天. ...

  2. 第三十一讲:UML类图(上)

    类名 成员变量:属性 成员函数:方法 访问权限-属性名-属性的类型 访问权限-方法名-返回值,还可以传递参数列表. 继承类的类图 JAVA里面类的访问权限只有两种:package(默认的访问权限)和p ...

  3. Bootstrap <基础三十一>插件概览

    在前面布局组件中所讨论到的组件仅仅是个开始.Bootstrap 自带 12 种 jQuery 插件,扩展了功能,可以给站点添加更多的互动.即使不是一名高级的 JavaScript 开发人员,也可以着手 ...

  4. COJ969 WZJ的数据结构(负三十一)

    WZJ的数据结构(负三十一) 难度级别:D: 运行时间限制:3000ms: 运行空间限制:262144KB: 代码长度限制:2000000B 试题描述 A国有两个主基站,供给全国的资源.定义一个主基站 ...

  5. NeHe OpenGL教程 第三十一课:加载模型

    转自[翻译]NeHe OpenGL 教程 前言 声明,此 NeHe OpenGL教程系列文章由51博客yarin翻译(2010-08-19),本博客为转载并稍加整理与修改.对NeHe的OpenGL管线 ...

  6. 三十一、Java图形化界面设计——布局管理器之GridLayout(网格布局)

    摘自http://blog.csdn.net/liujun13579/article/details/7772491 三十一.Java图形化界面设计--布局管理器之GridLayout(网格布局) 网 ...

  7. JAVA之旅(三十一)——JAVA的图形化界面,GUI布局,Frame,GUI事件监听机制,Action事件,鼠标事件

    JAVA之旅(三十一)--JAVA的图形化界面,GUI布局,Frame,GUI事件监听机制,Action事件,鼠标事件 有段时间没有更新JAVA了,我们今天来说一下JAVA中的图形化界面,也就是GUI ...

  8. Java进阶(三十一) Web服务调用

    Java进阶(三十一) Web服务调用 前言 有朋友问了一个问题:如何调用已知的音乐服务接口,服务文档如下: https://www.evernote.com/shard/s744/sh/c37cd5 ...

  9. Gradle 1.12用户指南翻译——第三十一章. FindBugs 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

随机推荐

  1. Servlet 获取多个参数

    <html><head> <title>First Servlet</title></head><body bgColor=" ...

  2. 学习笔记(三):jQuery之DOM

    1.jQuery属性. 获取元素属性的语法: attr(name)                   例子:$("#img1").attr("src"); 设 ...

  3. Spark SQL概念学习系列之Spark SQL基本原理

    Spark SQL基本原理 1.Spark SQL模块划分 2.Spark SQL架构--catalyst设计图 3.Spark SQL运行架构 4.Hive兼容性 1.Spark SQL模块划分 S ...

  4. C#中数组与ArrayList的简单使用

    1. 多维数组 2. 锯齿数组 3. 数组的常用操作 4. ArrayList 1. 多维数组 多维数组:行数和列数在定义时已确定 string[,] arr = new string[2, 3]; ...

  5. 洛谷P1876 开灯

    题目背景 该题的题目是不是感到很眼熟呢? 事实上,如果你懂的方法,该题的代码简直不能再短. 但是如果你不懂得呢?那...(自己去想) 题目描述 首先所有的灯都是关的(注意是关!),编号为1的人走过来, ...

  6. Android开发人员应该知道的Kotlin

    本文来源于我在InfoQ中文站翻译的文章,原文地址是:http://www.infoq.com/cn/news/2016/01/kotlin-android Android开发人员在语言限制方面面临着 ...

  7. POJ 3617 Best Cow Line ||POJ 3069 Saruman's Army贪心

    带来两题贪心算法的题. 1.给定长度为N的字符串S,要构造一个长度为N的字符串T.起初,T是一个空串,随后反复进行下面两个操作:1.从S的头部删除一个字符,加到T的尾部.2.从S的尾部删除一个字符,加 ...

  8. 8、for 、emumrate、range、if

    1.for循环用户按照顺序循环可迭代对象中的内容,PS:break.continueli = [11,22,33,44]for item in li: print item 2.enumrate 为可 ...

  9. 【例题 6-15 UVA - 10129】Play on Words

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 拓扑大水题 [代码] #include <bits/stdc++.h> using namespace std; con ...

  10. Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor Example(ScheduledThreadPoolExecutor例子——了解如何创建一个周期任务)

    Welcome to the Java Scheduler Example. Today we will look into ScheduledExecutorService and it's imp ...