技巧篇(2):hibernate中事务模板和获取Session模板(open和getcurrent)

文章中所涉及openSession()和getCurrentSession(),在hibernate总结篇会主要说明他们的区别以及使用场景,以及缓存的概念也会说明(一级缓存Session和二级缓存),还有关于query查询接口也会说明。本文章的代码都是优化过的模板,当你在学习或者开发的时候都可以拿来套用。


在hibernate中回滚事务,这就是我们以后写具体事务(增加、修改、删除、查询)的模板

package test;

import domain.Employee;

import Util.sessionUtil;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.query.Query;

import java.util.List;

public class testMoban {

public static  void main(String[] args){

testMoban testMoban =new testMoban();

//  testMoban.add();

// testMoban.update();

//  testMoban.delete();

//      testMoban.query();

}

//添加一个用户

    public void add(){

Session session= sessionUtil.getCurrentSession();

Transaction ts=null;

try{

ts = session.beginTransaction();

//添加

            Employee employee =new Employee();

employee.setName("小王");

employee.setAge(20);

employee.setDuty("java开发工程师");

// 保存

            session.save(employee);

//提交

            ts.commit();

}catch (Exception e){

if(ts!=null){

ts.rollback();

}

}finally {

//关闭Session

            if(session!=null&&session.isOpen()){

session.close();

}

}

}

//更新用户

    public void update(){

Session session= sessionUtil.getCurrentSession();

Transaction ts=null;

try{

ts = session.beginTransaction();

//***********************************************************************//

            Employee employee =(Employee) session.load(Employee.class,1);

employee.setName("小张张");

employee.setAge(29);

//************************************************************************//

            ts.commit();

}catch (Exception e){

if(ts!=null){

ts.rollback();

}

}finally {

//关闭Session

            if(session!=null&&session.isOpen()){

session.close();

}

}

}

//删除用户

    public void delete(){

Session session= sessionUtil.getCurrentSession();

Transaction ts=null;

try{

ts = session.beginTransaction();

//*************************************************************************//

            Employee employee =(Employee) session.load(Employee.class,6);

session.delete(employee);

//*************************************************************************//

            ts.commit();

}catch (Exception e){

if(ts!=null){

ts.rollback();

}

}finally {

//关闭Session

            if(session!=null&&session.isOpen()){

session.close();

}

}

}

//使用query进行查询(重点)

    public void query(){

Session session= sessionUtil.getCurrentSession();

Transaction ts=null;

try{

ts = session.beginTransaction();

//*************************************************************************//

//获取query引用,这里的Employee不是对应数据库的表,而是domain类

            Query query =session.createQuery("from Employee where id=1");

//通过List方法获取结果,这个List会自动封装成对应的对象

            List list=query.list();

for (Employee e:list){

System.out.println(e.getName()+"  "+e.getDuty());

}

//*************************************************************************//

            ts.commit();

}catch (Exception e){

if(ts!=null){

ts.rollback();

}

}finally {

//关闭Session

            if(session!=null&&session.isOpen()){

session.close();

}

}

}

}

直接获取session,其中分为openSession()和getCurrentSession(),并且有了这个工具类,我们想要得到getCurrentSession()不用在配置文件中配置了,模版如下,以后就用这个。

package Util;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import javax.security.auth.login.Configuration;

final public class sessionUtil {

private static SessionFactorysessionFactory=null;

//使用线程的局部模式

    private static  ThreadLocalthreadLocal=new ThreadLocal();

private sessionUtil(){};

static {

try {

sessionFactory=new org.hibernate.cfg.Configuration().configure().buildSessionFactory();

}catch (Throwable ex){

throw new ExceptionInInitializerError(ex);

}

}

//获得全新的Session,(openSession)

    public static Session openSession(){

return sessionFactory.openSession();

}

//获取和线程关联的线程session,(getCurrentSession)

    public static Session getCurrentSession(){

Session session = (Session)threadLocal.get();

if(session==null){

session=sessionFactory.openSession();

//把Session对象设置到threadLocal,相当于已经和线程绑定

            threadLocal.set(session);

}

return session;

}

}

这里在多加一个我自己一开始写的(没升级过的),获得SessionFactory的工具类。这个也可以用。

package Util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

//在使用hibernate开发项目时,保证只有一个sessionFactory(因此这里做成一个单例模式,直接调用就好)

//一个数据库对应一个sessionFactory

final public class sessionFactoryUtil {

private static SessionFactorysessionFactory=null;

private sessionFactoryUtil(){

}

static {

sessionFactory=new Configuration().configure().buildSessionFactory();

}

public static SessionFactory getSessionFactory(){

return sessionFactory;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文中我们介绍并比较两种最流行的开源持久框架:iBATIS和Hibernate,我们还会讨论到Java Persi...
    大同若鱼阅读 4,371评论 4 27
  • Hibernate: 一个持久化框架 一个ORM框架 加载:根据特定的OID,把一个对象从数据库加载到内存中OID...
    JHMichael阅读 2,030评论 0 27
  • 本文包括:1、Hibernate的持久化类2、Hibernate 持久化对象的三个状态(难点)3、Hibernat...
    廖少少阅读 1,512评论 0 13
  • 一. Java基础部分.................................................
    wy_sure阅读 3,859评论 0 11
  • 人总是没办法的困在匆忙之中,匆匆的忘记了很多事情, 忘记了欣赏孩子的笑容,忽略了你爱的人对你说的关切, 急切的要求...
    星空下的深渊阅读 177评论 0 1