zoukankan      html  css  js  c++  java
  • 封装hibernate 初始化类 方便调用 (静态单例模式)

    因为每次用增删改查时都需要用到session,所以我们直接封装一个类,需要的时候只需要调用即可

    package com.itnba.maya.bean;
    
    import org.hibernate.*;
    import org.hibernate.cfg.*;
    import javafx.util.*;
    
    public class HibernateUtil {
    	//定义常量是为了实现单例,不让随便new
    	private static final SessionFactory factory = BuilderFactory();
    	//ThreadLocal<Session>不是集合,是线程锁,为了单线程安全
    	private static final ThreadLocal<Session> threadlocal = new ThreadLocal<Session>();
    	private static SessionFactory BuilderFactory() {
    		Configuration conf = new Configuration().configure();
    		return conf.buildSessionFactory();
    	}
    	public static Session getSession(){
    		//先获取线程锁中的session
    		Session session = threadlocal.get();
    		if(session == null){
    			//如果没有session就新建一个session赋值给threadlocal
    			session = factory.openSession();
    			threadlocal.set(session);
    		}
    		return session;
    	}
    	public static void closeSession(){
    		//先获取线程锁中的session
    		Session session = threadlocal.get();
    		if(session != null){
    			//将session关闭之后再给threadlocal赋个null,方便其他线程使用
    			session.close();
    			threadlocal.set(null);
    		}
    	}
    	
    	
    }
    

      我们引用看一下能不能使用

    package com.itnba.maya.bean;
    
    import org.hibernate.*;
    
    public class TestFruit {
    
    	public static void main(String[] args) {
    		Fruit f = new Fruit();
    		f.setIds("i001");
    		f.setName("西瓜");
    		f.setPrice(10.0);
    		f.setSource("张店");
    		f.setNumbers(100);
    		f.setImage("无");
    		try{
    			Session session = HibernateUtil.getSession();
    			session.beginTransaction();
    			session.save(f);
    			session.getTransaction().commit();
    		}
    		catch(Exception e){
    			e.printStackTrace();
    		}
    		finally {
    			HibernateUtil.closeSession();
    		}
    	}
    
    }
    

      运行一下看下结果:

    看下数据库中是否改变

    这样我们就成功的将hibernate 初始化类封装好了,可以在需要时直接引用即可

  • 相关阅读:
    Eclipse安装Hadoop插件
    (转)Ubuntu14.0.4中hadoop2.4.0伪分布模式配置
    Hadoop--DataNode无法启动
    启动与关闭hadoop
    hadoop中执行命令时发生错误
    strings命令
    Deriving data from ElasticSearch Engine
    elasticsearch data importing
    reading words in your computer and changing to female voice, linux festival text2wave saving wav files
    DDNS client on a Linux machine
  • 原文地址:https://www.cnblogs.com/dnf1612/p/6497596.html
Copyright © 2011-2022 走看看