⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 basehibernatedao.java

📁 用户可以登陆注册对房屋信息的增删改查功能
💻 JAVA
字号:
package com.qhit.kgdyffje.hibernater.util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

public abstract class BaseHibernateDAO {
	
	protected Session getSession() {
    	return HibernateSessionFactory.getSession();  
    }
  
	protected boolean save(Object item){
		Session ss=null;
		Transaction tx=null;
		try {
			ss=getSession();
            tx = ss.beginTransaction();
        	ss.save(item);
        	tx.commit();
        	return true;
        } catch (RuntimeException re) {
        	if(null!=tx){tx.rollback();}
            re.printStackTrace();
        }finally{
        	if(ss.isOpen())ss.close();
        }
        return false;
	}
	
	protected Object load(int id,Class clazz){
		try { 
			Object item = getSession()
            	.get(clazz, id);
			return item;
        } catch (RuntimeException re) {
            throw re;
        }
	}
	
	protected boolean delete(int id,Class clazz){
		Transaction tx = null;
		Session session = getSession();
		try {
        	tx = session.beginTransaction();
        	session.delete(this.load(id, clazz));
        	tx.commit();
        	return true;
        } catch (RuntimeException re) {
            tx.rollback();
        	re.printStackTrace();            
        }finally{
        	if(session.isOpen())session.close();
        }		
        return false;
	}
	
	protected boolean update(Object item){
		Transaction tx=null;
		Session session=getSession();
		try {
            tx = session.beginTransaction();
        	session.merge(item);
        	tx.commit();
        	return true;
        } catch (RuntimeException re) {
            if(null!=tx)tx.rollback();
            re.printStackTrace();
        }finally{
        	if(session.isOpen())session.close();
        }
        return false;
	}
	
	protected List search(Object condition,Class clazz){
		try {
            List results = getSession()
                    .createCriteria(clazz)
                    .add(Example.create(condition))
            .list();
            return results;
        } catch (RuntimeException re) {
            throw re;
        }
	}
	public List findByExample(Object instance) {
		try {
			List results = getSession().createCriteria(
					instance.getClass()).add(
					Example.create(instance)).list();

			return results;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	public List findAll(Class clazz) {
		try {
			String queryString = "from clazz";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -