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. 【整理】C#文件操作大全(SamWang)

    [整理]C#文件操作大全(SamWang) 文件与文件夹操作主要用到以下几个类: 1.File类: 提供用于创建.复制.删除.移动和打开文件的静态方法,并协助创建 FileStream 对象. msd ...

  2. openstack-ansible Chapter 4. Deployment configuration

    Initial environment configuration Copy the contents of the /opt/openstack-ansible/etc/openstack_depl ...

  3. 解决mssql for linux 中文乱码问题

    什么叫一波未平一波又起,这就是,好不容易安装完成了,在用的时候居然出现了乱码,很是头疼,但还是解决了这个蛋疼的问题,在windows中使用mssql这么久,从来没出现过中文乱码的情况,具体原因是出现在 ...

  4. EF-局部更新

    // ////1 public Task ReservedQuantity(long productId, long skuId, int reservedQuantity, long userId) ...

  5. javascript测试框架mocha

    node测试框架mocha 简单.灵活.有趣,mocha是一个功能丰富的javascript测试框架,运行在node和浏览器中,使异步测试变得更加简单有趣.http://mochajs.org/ 安装 ...

  6. Python — 多线程与多进程

    1.多线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位,一个进程可以包含多个线程.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线 ...

  7. Swift中如何使用 #if DEBUG

    Swift暂时还不支持大多数的预处理宏操作,但是可以支持“#if/#else/#endif”语句. 下面进行简单的设置使 #if DEBUG 有效,更详细的内容见:http://stackoverfl ...

  8. 神经网络卷积层 要回计算output的维度 input 28 卷积是3x3 则output是26 但是channel是卷积核的数量

    model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_s ...

  9. mysql ORM框架及SQLAlchemy

    一 介绍 SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取 ...

  10. UnityGUI扩展实例:图片挖洞效果 Mask的反向实现

    转载自 https://www.taidous.com/forum.php?mod=viewthread&fid=211&tid=55259 我想大家在用uGUI做界面时,可能经常会碰 ...