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. ubuntu/centos printk 终端中不能打印信息及解决办法

    今天用ubuntu来调试信息,printk死活打印不出信息,即使把级别跳到<0>,即KERN_ALERT也不行,后再搜了好长时间网络, 这个地址:http://bbs.chinaunix. ...

  2. ES6-let命令

    let命令 用于声明变量,但是声明的变量只能在let命令所在的代码块内有效, { let a = 10; var b = 1; } 其中,a在代码块的外部是调用不到的.对于for循环的计数器里面,就很 ...

  3. ural 1039 树dp

    http://acm.timus.ru/problem.aspx?space=1&num=1039 1039. Anniversary Party Time limit: 0.5 second ...

  4. 达观数据分析平台架构和Hive实践——TODO

    转自: http://www.infoq.com/cn/articles/hadoop-ten-years-part03 编者按:Hadoop于2006年1月28日诞生,至今已有10年,它改变了企业对 ...

  5. hbase-0.20.6/bin/hbase-daemon.sh: Permission denied

    部署hbase全分布式时,出现以下错误:主机的hbase启动了,但是从机的没启动[root@centos7- my.shells]# start-hbase.sh Java HotSpot(TM) - ...

  6. uva11078 - Open Credit System(动态维护关键值)

    这道题使用暴力解法O(n*n)会超时,那么用动态维护最大值可以优化到O(n).这种思想非常实用. #include<iostream> #include<cstdio> #in ...

  7. 安装Aptana时检测不到已经安装的Nodejs

    1.环境前提 已经安装了Git和Nodejs,在安装Aptana时任然提示如下错误: Failed to correctly acquire installer_nodejs_windows.msi ...

  8. STL迭代器辅助函数——advance

    Advance(i, n) increments the iterator i by the distance n. If n > it it , the call has no effect. ...

  9. stl_hash_map.h

    stl_hash_map.h // Filename: stl_hash_map.h // Comment By: 凝霜 // E-mail: mdl2009@vip.qq.com // Blog: ...

  10. Ubuntu 安装arm-linux-gcc编译器

    /********************************************************************************** * Ubuntu 安装arm-l ...