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. MySQL 汉字拼音

    http://blog.csdn.net/u012076316/article/details/54951365 http://www.cnblogs.com/diony/p/5483108.html ...

  2. 51NOD——T 1079 中国剩余定理

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1079 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难 ...

  3. 使用Spring框架的好处

    转自:https://www.cnblogs.com/hoobey/p/6032506.html 在SSH框假中spring充当了管理容器的角色.我们都知道Hibernate用来做持久层,因为它将JD ...

  4. Java – Reading a Large File Efficiently--转

    原文地址:http://www.baeldung.com/java-read-lines-large-file 1. Overview This tutorial will show how to r ...

  5. AJAX有关的请求协议及HTTP报文

    URI:统一资源标识符 URI=URL+URNURL:统一资源定位符URN:统一资源名称 上边的图片编号对应下边的编号说明: 1.HTTP(占90%市场)/HTTPS/FTP 传输协议(可以理解为快递 ...

  6. 深度解析VC中的消息(转发)

    http://blog.csdn.net/chenlycly/article/details/7586067 这篇转发的文章总结的比较好,但是没有告诉我为什么ON_MESSAGE的返回值必须是LRES ...

  7. MWPhotoBrowser 属性详解 和代理解释

    --------0.MWPhoto简单属性解释---------------- MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString: ...

  8. UVA 11367 - Full Tank? dijkstra+DP

    传送门:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&a ...

  9. BUFSIZ

    转http://www.judymax.com/archives/262 今天在看示例程序时冒出来一句args = emalloc(BUFSIZ); BUFSIZ是什么意思,查了一下才明白. 这是st ...

  10. 手把手教你----MyEclipse中 配置 Tomcat

    电脑上配置Tomcatserver 安装Tomcat并配置环境变量 測试是否配置成功 MyEclipse中配置Tomcat 想要开发Java Web的程序.首先在MyEclipse中必须配置Tomca ...