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. Java编程思想 两个主函数

    //: initialization/DynamicArray.javapackage initialization; /* Added by Eclipse.py */// Array initia ...

  2. 配置网卡为vlan trunk

    http://www.microhowto.info/tutorials/802.1q.html Configure an Ethernet interface as a VLAN trunk hos ...

  3. [STL]vector与排序算法

    vector与算法 头文件中包含大量与 vector 相关的算法,这些算法同样适用于其它容器,比如 std::list 等. 排序(Sort) 相关函数: std::sort :普通排序 defaul ...

  4. MinGW main()

    MinGW没有wmain入口函数,为了获取宽字符的参数,可以用系统API函数GetCommandLineW. main.cpp #include <iostream> #include & ...

  5. Django 基础 web框架本质

    Web框架本质 我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. import socket sk ...

  6. commons-dbcp连接池的使用

    数据库连接池 池参数(所有池参数都有默认值): 初始大小: 最小空闲连接数: 增量:一次创建的最小单位(5个) 最大空闲连接数:12个 最大连接数:20个 最大的等待时间:1000毫秒 四大连接参数: ...

  7. hdoj-1004-Let the Balloon Rise(map排序)

    map按照value排序 #include <iostream> #include <algorithm> #include <cstring> #include ...

  8. CCEditBox

    EditBox 创建添加 以及 一些函数参数的解析 #include "GUI/CCEditBox/CCEditBox.h" #include "GUI/CCContro ...

  9. nodejs读取excel内容批量替换并生成新的html和新excel对照文件

    因为广告投放需要做一批对外投放下载页面,由于没有专门负责填充页面的编辑同学做,只能前端来做了, 拿到excel看了一下,需要生成200多个文件,一下子懵逼了. 这要是来回复制粘贴太low了 正好最新用 ...

  10. 输入一个链表,输出该链表中倒数第k个结点

    package suanfa; import suanfa.doubleLinkedList.Node; public class solution { public Node find(Node h ...