Java Hibernate5完整帮助类

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




HibernateSessionFactory.java

package basic;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * 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 HibernateSessionFactory {

    /** 
     * 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

	static {
    	try {
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * 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();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} 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 hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

DoWork.java

package basic;

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.jdbc.Work;
 
public class DoWork implements Work{

	private Connection connection;
	public void execute(Connection con) throws SQLException {
			connection=con;
	}
	public Connection getConnection() {
		return connection;
	}
}

HibernateUtils.java

package basic;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;

public class HibernateUtils {
	
    /**
     * 根据cls对应表的主键属性id来查询并返回cls类型的对象
     * @param cls 要查询的Hibernate的表映射类对象名
     * @param id 查询所用的对应主键的值
     * @return 返回的cls类型的对象
     */
    public Object findById(Class cls, Serializable id) {
        Session session = HibernateSessionFactory.getSession();
        try {
            Object obj = session.get(cls, id);
            session.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }  
	
	/**
     * 添加对象到数据库中
     * @param obj 实体对象
     * @return 返回主键id, null则表示添加失败 
     */
	public Object insert(Object obj) {
		Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            Serializable key = session.save(obj);
            tx.commit(); // 持久化操作
            session.close();
            return key;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return null;
    }
	
    /**
     * 无参数的sql实现添加
     * @param sql sql添加语句
     * @return boolean true 成功    false 失败
     */
    public boolean insert(String sql) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql);
            int row = ptmt.executeUpdate();

            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
	
    /**
     * 有参数的sql实现添加
     * @param sql sql添加语句
     * @param para Object[] 参数值数组
     * @return boolean true 成功    false 失败
     */
    public boolean insert(String sql, Object[] para) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql);
            for (int i = 0; i < para.length; i++) {
                ptmt.setObject(i + 1, para[i]);
            }
            int row = ptmt.executeUpdate();
            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
	
    /**
     * list批量添加到数据库中
     * @param list List<Object>
     * @return int 影响行数
     */
    public int insert(List<Object> list) {
        if(list.size()<1){
            return 0;
        }
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        int count=0;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            for (Object obj : list) {
                session.save(obj);
                count++;
                if(list.size()%100==0){   //每一百条刷新并写入数据库  
                    session.flush();  
                    session.clear();  
                }  
            }
            tx.commit(); // 持久化操作

            session.close();
            return count;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return 0;
    }
    
    /**
     * 数据删除
     * @param obj 实体对象
     * @return boolean true 成功    false 失败
     */
    public boolean delete(Object obj) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            session.delete(obj);
            tx.commit(); // 持久化操作 session.close();
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
    
    /**
     * 无参数的sql实现删除
     * @param sql sql删除语句
     * @return boolean true 成功    false 失败
     */
    public boolean delete(String sql) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql);
            int row = ptmt.executeUpdate();

            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
    
    /**
     * 有参数的sql实现删除
     * @param sql sql删除语句
     * @param para Object[] 参数值数组
     * @return boolean true 成功    false 失败
     */
    public boolean delete(String sql, Object[] para) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql);
            for (int i = 0; i < para.length; i++) {
                ptmt.setObject(i + 1, para[i]);
            }
            int row = ptmt.executeUpdate();
            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
    
    /**
     * 批量删除
     * @param sql sql删除语句:delete from T_Book
     * @param identity String 字段名称
     * @param mulId 删除条件:1,2,3
     * @return int 返回影响行数
     */
    public int delete(String sql,String identity,String mulId) {
        Session session = HibernateSessionFactory.getSession();
        
        DoWork work = new DoWork();
        session.doWork(work);
        
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql+" where "+identity+" in ("+mulId+")");
            int row = ptmt.executeUpdate();

            tx.commit(); // 持久化操作 
            session.close();

            return row;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return 0;
    }
    
    /**
     * 数据修改
     * @param obj 实体对象
     * @return boolean true 成功    false 失败
     */
    public boolean update(Object obj) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            session.update(obj);
            tx.commit(); // 持久化操作
            session.close();
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
    
    /**
     * 无参数的sql实现更新
     * @param sql sql更新语句
     * @return boolean true 成功    false 失败
     */
    public boolean update(String sql) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
//            Connection con = session.connection(); //hibernate3.3以下使用该方法
            PreparedStatement ptmt = con.prepareStatement(sql);
            int row = ptmt.executeUpdate();

            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
    
    /**
     * 有参数的sql实现更新
     * @param sql sql更新语句
     * @param para Object[] 参数值数组
     * @return boolean true 成功    false 失败
     */
    public boolean update(String sql, Object[] para) {
        Session session = HibernateSessionFactory.getSession();
        DoWork work = new DoWork();
        session.doWork(work);
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            // 将会话Session对象转换成jdbc的Connection
            Connection con = work.getConnection();
            PreparedStatement ptmt = con.prepareStatement(sql);
            for (int i = 0; i < para.length; i++) {
                ptmt.setObject(i + 1, para[i]);
            }
            int row = ptmt.executeUpdate();
            tx.commit(); // 持久化操作 
            session.close();

            if (row > 0)
                return true;
            else
                return false;

        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return false;
    }
	
    /**
     * 无参数的hql实现查询
     * @param hql String 符合hql结构的无参数查询语句
     * @return List  失败返回null
     */
    public List select(String hql) {
    	Session session = HibernateSessionFactory.getSession();
        try {
        	Query  query = session.createQuery(hql);
            List list =query.getResultList();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 带有参数的hql实现查询
     * @param hql String 符合hql结构的有参数查询语句
     * @param para Object[] 参数值数组
     * @return List  失败返回null
     */
    public  List select(String hql, Object[] para) {
        Session session = HibernateSessionFactory.getSession();
        try {
        	Query  query = session.createQuery(hql);
            // 根据para设置参数
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            List list =query.getResultList();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /***
     * 无参查询的sql语句
     * @param sql
     * @return
     */
    public List selectSql(String sql){
    	Session session = HibernateSessionFactory.getSession();
        try {
            NativeQuery  query = session.createNativeQuery(sql);
            query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List list =query.getResultList();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 带参查询的sql语句
     * @param sql
     * @param para
     * @return
     */
    public List selectSql(String sql,Object para[]){
        Session session = HibernateSessionFactory.getSession();
        try {
            NativeQuery  query = session.createNativeQuery(sql);
            query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            List list =query.getResultList();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 带参查询的sql语句
     * @param sql
     * @param cls
     * @return
     */
    public <T> List<T> selectSql(String sql,Class<T> cls){
    	Session session = HibernateSessionFactory.getSession();
        try {
            NativeQuery  query = session.createNativeQuery(sql);
            query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(cls));
            List list =query.getResultList();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 带参查询的sql语句
     * @param sql
     * @param para
     * @param cls
     * @return
     */
    public <T> List<T> selectSql(String sql,Object para[],Class<T> cls){
        Session session = HibernateSessionFactory.getSession();
        try {
            NativeQuery  query = session.createNativeQuery(sql);
            query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(cls));
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            List list =query.getResultList();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 无参数的sql实现查询行数
     * @param sql sql查询count语句
     * @return count值
     */
    public Object selectCount(String sql){
        Session session = HibernateSessionFactory.getSession();
        try {
            Object count =  session.createSQLQuery(sql).uniqueResult();
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return 0;
    }
    
    /**
     * 有参数的sql实现查询行数
     * @param sql sql查询count语句
     * @param para Object[] 参数值数组
     * @return count值
     */
    public Object selectCount(String sql,Object para[]){
        Session session = HibernateSessionFactory.getSession();
        try {
            NativeQuery query = session.createNativeQuery(sql);
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            Object val =query.getResultList().get(0);
            return val;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return 0;
    }
    
}

JacksonUtil.java

package basic;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	static {
		mapper.setSerializationInclusion(Include.NON_EMPTY);  
	}
	
	//json转bean
	public static <T> T deserialize(String json,Class<T> cls){
        T t = null;
        try{
            t=mapper.readValue(json, cls);
        }catch (Exception ex){
            return null;
        }
        return t;
    }

	//json数组转bean
    public static <T> List<T> decode(String json,Class<T> cls) {
        List<T> list;
       try{
           JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, cls);
           list=(List<T>)mapper.readValue(json, javaType);
       }
       catch (Exception ex){
           return null;
       }
        return list;
    }
    
    //bean转json
    public static String beanToJson(Object obj) {
    	String json="";
    	try {
			json=mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return json;
    }
    
    //list转json
    public static String listToJson(List list){
    	String json="";
    	try {
			json=mapper.writeValueAsString(list);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return json;
    }
}

原文链接:https://www.idaobin.com/archives/2246.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

9 × = 54