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的更多相关文章

  1. 深入浅出Struts2+Spring+Hibernate框架

    一.深入浅出Struts2 什么是Struts2? struts2是一种基于MVC的轻量级的WEB应用框架.有了这个框架我们就可以在这个框架的基础上做起,这样就大大的提高了我们的开发效率和质量,为公司 ...

  2. spring声明式事务管理总结

    事务配置 首先在/WEB-INF/applicationContext.xml添加以下内容: <!-- 配置事务管理器 --> <bean id="transactionM ...

  3. Hibernate(二)__简单实例入门

    首先我们进一步理解什么是对象关系映射模型? 它将对数据库中数据的处理转化为对对象的处理.如下图所示: 入门简单实例: hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中 ...

  4. SSH框架使用注解简化代码

    注释的优势: 1.最简单直接的优势就是减少了配置文件的代码量. 2.注释和Java代码位于一个文件中,而XML 配置采用独立的配置文件.配置信息和 Java 代码放在一起,有助于增强程序的内聚性.而采 ...

  5. SSH(Struts2+Spring4+HIbernate5)的简化

    今天给大家带来的是一个简单的新闻发布系统 首先在学习过程中我是深有体会,做事情不要浮躁,不要想着一口吃下一个胖子, 最最重要的是理解,理解透了学什么东西都是随心所欲的. 开发环境:win10系统 jd ...

  6. 浅谈Hibernate入门

    前言 最近打算做一个自己的个人网站,经过仔细思考,打算使用hibernate作为开发的ORM框架,因此各种找资料,由于本人是刚刚接触这技术的,所以就找了比较基础的知识来分享下 基本概述 Hiberna ...

  7. 新手SSH基础框架搭建

    SSH 为 struts+spring+hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架. 首先我们先了解SSH的框架所需的包和基本概念: 一.下面我们先来了解一下strut ...

  8. Spring声明事务管理

    首先我们先了解事务,什么是事务? 简单来说就是要么全部成功,要么什么都不做. 为什么要使用事务? 比如说常用银行系统的例子,如果没有用事务,有人在存入钱的时候出了问题,那么银行系统数据库的数据没有改变 ...

  9. java必备基础知识点

    Java基础 1. 简述Java的基本历史 java起源于SUN公司的一个GREEN的项目,其原先目的是:为家用消费电子产品发送一个信息的分布式代码系统,通过发送信息控制电视机.冰箱等 2. 简单写出 ...

随机推荐

  1. 直播P2P技术1-技术入门

    1. 直播协议 直播协议主要有RTMP,HLS,MPEG-DASH,RTSP,HTTP-FLV等.每种协议都各有长短,比如RTMP延迟低,但诞生于Adobe,依赖于Flash Player,在如今FL ...

  2. JavaWeb中的中文编码问题

    一.为什么要编码? 1.在计算机中存储信息的最小单元是1字节,即8个bit,所以能表示的字符范围是0~255个. 2.人类要表示的符号太多,无法用1个字节来完全表示. 这就是矛盾,要解决这个矛盾,就出 ...

  3. IIS7 配置PHP服务器

    安装PHP Manager: 1)访问 http://phpmanager.codeplex.com/releases/view/69115 下载PHP Manager.其中,x86 为32位 Win ...

  4. [项目部署] CentOs7 安装 MySQL/Tomcat/JDK 笔记

    0.安装 MySQL cd /usr/local/ # 新增yum源 rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-.no ...

  5. java.net.SocketException: No buffer space available 异常

    http://stackoverflow.com/questions/10088363/java-net-socketexception-no-buffer-space-available-maxim ...

  6. python 实现一个TwoSum的例子

    今天无意中看到一个题目,也不是很难,就想着用python实现以下: 题目是数组中的两个数相加等于输入的一个target,然后输出数组的下标. 比如: [1,2,3,4,5,6] target=7  返 ...

  7. vue项目打包注意的地方

    打包有两种方式: 第一种方式:1.更改config文件夹下prod.env.js下的地址: 2.将config文件夹下index.js中build下改为 assetsPublicPath: '', 第 ...

  8. SpringCloud教程 | 第五篇: 路由网关(zuul)

    在微服务架构中,需要几个基础的服务治理组件,包括服务注册与发现.服务消费.负载均衡.断路器.智能路由.配置管理等,由这几个基础组件相互协作,共同组建了一个简单的微服务系统.一个简答的微服务系统如下图: ...

  9. Linux-监控与安全运维之cacti

    一:cacti简介 Cacti 在英文中的意思是仙人掌的意思,Cacti是一套基于PHP,MySQL,SNMP及RRDTool开发的网络流量监测图形分析工具.它通过snmpget来获取数据,使用 RR ...

  10. git常用命令收藏

    git init //初始化本地git环境 git clone XXX//克隆一份代码到本地仓库 git pull //把远程库的代码更新到工作台 git pull --rebase origin m ...