MySessionFactory
package com.ORM; 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. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class MySessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private MySessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* 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();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
MySessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }
package com.service; import java.util.List; import com.ORM.*;
import com.base.*;
import org.hibernate.*; /** 系统用户管理接口实现 */
public class AdminServiceImpl extends BaseLog implements AdminService { /** 系统管理员登录 */
public Admin adminLogin(String loginName, String loginPwd) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
Admin admin = null;
try{
String hql = "select a from Admin as a where a.loginName=:loginName and a.loginPwd=:loginPwd";
Query query = session.createQuery(hql);
query.setString("loginName", loginName);
query.setString("loginPwd", loginPwd);
query.setMaxResults(1);
tx = session.beginTransaction();
admin = (Admin)query.uniqueResult();
tx.commit();
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的adminLogin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return admin;
} /** 新增管理员 */
public boolean addAdmin(Admin admin) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
boolean status = false;
try{
tx = session.beginTransaction();
session.save(admin);
tx.commit();
status = true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的addAdmin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return status;
} /** 浏览管理员 */
public List browseAdmin() throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
List list = null;
try{
Query query = session.createQuery("from Admin as a order by a.id");
tx = session.beginTransaction();
list = query.list();
tx.commit();
if (!Hibernate.isInitialized(list))Hibernate.initialize(list);
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的browseAdmin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return list;
} /** 删除指定的管理员 */
public boolean delAdmin(Integer id) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
boolean status = false;
try{
tx = session.beginTransaction();
Admin admin = (Admin)session.load(Admin.class, id);
session.delete(admin);
tx.commit();
status = true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的delAdmin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return status;
} /** 装载指定的管理员 */
public Admin loadAdmin(Integer id) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
Admin admin = null;
try{
tx = session.beginTransaction();
admin = (Admin)session.get(Admin.class, id);
tx.commit();
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的loadAdmin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return admin;
} /** 更新管理员 */
public boolean updateAdmin(Admin admin) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
boolean status = false;
try{
tx = session.beginTransaction();
session.update(admin);
tx.commit();
status = true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行AdminServiceImpl类中的updateAdmin方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return status;
}
}
MySessionFactory的更多相关文章
- 深入浅出Struts2+Spring+Hibernate框架
一.深入浅出Struts2 什么是Struts2? struts2是一种基于MVC的轻量级的WEB应用框架.有了这个框架我们就可以在这个框架的基础上做起,这样就大大的提高了我们的开发效率和质量,为公司 ...
- spring声明式事务管理总结
事务配置 首先在/WEB-INF/applicationContext.xml添加以下内容: <!-- 配置事务管理器 --> <bean id="transactionM ...
- Hibernate(二)__简单实例入门
首先我们进一步理解什么是对象关系映射模型? 它将对数据库中数据的处理转化为对对象的处理.如下图所示: 入门简单实例: hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中 ...
- SSH框架使用注解简化代码
注释的优势: 1.最简单直接的优势就是减少了配置文件的代码量. 2.注释和Java代码位于一个文件中,而XML 配置采用独立的配置文件.配置信息和 Java 代码放在一起,有助于增强程序的内聚性.而采 ...
- SSH(Struts2+Spring4+HIbernate5)的简化
今天给大家带来的是一个简单的新闻发布系统 首先在学习过程中我是深有体会,做事情不要浮躁,不要想着一口吃下一个胖子, 最最重要的是理解,理解透了学什么东西都是随心所欲的. 开发环境:win10系统 jd ...
- 浅谈Hibernate入门
前言 最近打算做一个自己的个人网站,经过仔细思考,打算使用hibernate作为开发的ORM框架,因此各种找资料,由于本人是刚刚接触这技术的,所以就找了比较基础的知识来分享下 基本概述 Hiberna ...
- 新手SSH基础框架搭建
SSH 为 struts+spring+hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架. 首先我们先了解SSH的框架所需的包和基本概念: 一.下面我们先来了解一下strut ...
- Spring声明事务管理
首先我们先了解事务,什么是事务? 简单来说就是要么全部成功,要么什么都不做. 为什么要使用事务? 比如说常用银行系统的例子,如果没有用事务,有人在存入钱的时候出了问题,那么银行系统数据库的数据没有改变 ...
- java必备基础知识点
Java基础 1. 简述Java的基本历史 java起源于SUN公司的一个GREEN的项目,其原先目的是:为家用消费电子产品发送一个信息的分布式代码系统,通过发送信息控制电视机.冰箱等 2. 简单写出 ...
随机推荐
- QT 带有菜单项的ToolButton
QToolBar *pToolBar = new QToolBar; QToolButton *pMenuBtn = new QToolButton; pMenuBtn->setText(tr( ...
- 在Windows下使用adb logcat grep
在Windows下使用adb logcat grep 会提示 因为grep 为Linux命令,所以不能使用.怎么办呢? 这时候可以用到babun 下载地址:http://babun.github.i ...
- Ubuntu linux背景指南:在开始之前需要知道哪些东西
1.摘要 Ubuntu是一个新的GNU/Linux衍生操作系统,其目标是更多地以用户为本以及桌面应用. 因此,Ubuntu的目的是消除安装的困难,在很大程度上靠自动配置和自动探测硬件解决 问题,无须用 ...
- Nagios的基本安装配置
//////////////////////nagios//////////////////////nagios原理:http://www.linuxidc.com/Linux/2013-11/927 ...
- Python快速学习-函数
函数定义总结: 1.定义函数时,需要确定函数名和参数个数:2.如果有必要,先对参数的数据类型进行检查:3.函数体内部可以用return随时返回函数结果:4.函数执行完毕没有return语句时,自动re ...
- 智课雅思词汇---十六、前缀hyper和hypo是反义词
智课雅思词汇---十六.前缀hyper和hypo是反义词 一.总结 一句话总结: hypertension 过度紧张:高血压(hyper+tension紧张) hypotension 低血压 1.ep ...
- Spring Boot配置文件详解:自定义属性、随机数、多环境配置
自定义属性与加载 我们在使用Spring Boot的时候,通常也需要定义一些自己使用的属性,我们可以如下方式直接定义: application-dev.yml com.didispace.blog: ...
- 51nod 1437
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1437 1437 迈克步 题目来源: CodeForces 基准时间限制: ...
- mysql字段设计坑
对varchar, char类型的字段进行排序 把价格设计成decimal的时候,要注意 "有效位数", "小数位数", 不然会发现,插入的时候最多达到上限
- UVA - 11212 Editing a Book (IDA*)
给你一个长度为n(n<=9)的序列,每次可以将一段连续的子序列剪切到其他地方,问最少多少次操作能将序列变成升序. 本题最大的坑点在于让人很容易想到许多感觉挺正确但实际却不正确的策略来避开一些看似 ...