Java Hibernate帮助类

(..•˘_˘•..) 版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创! (..•˘_˘•..)点击一下广告页面也是对博主的支持哦


恰饭广告




环境搭建:https://www.idaobin.com/archives/2109.html

分页存储过程:https://www.idaobin.com/archives/1230.html

gson帮助类:https://www.idaobin.com/archives/2120.html

hibernate3.3以上且不用spring框架的情况下,Hibernate中session.connection()的替代类

DoWork.java

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.jdbc.Work;
 
public class DoWork implements Work{
	//hibernate3.3以上且不用spring框架的情况下,Hibernate中session.connection()的替代方法
	private Connection connection;
	public void execute(Connection con) throws SQLException {
			connection=con;
	}
	public Connection getConnection() {
		return connection;
	}
}

HibernateUtil.java

package basic;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;


public class HibernateUtil {

	/**
     * 添加对象到数据库中
     * @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;

    }
    
    /**
     * 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;

    }

    /**
     * 数据修改
     * @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;

    }

    /**
     * 无参数的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.list();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }

    /**
     * 实体查询
     * @param cls 要查询的Hibernate的表映射类对象名
     * @return List  失败返回null
     */
    public <T> List select(Class<T> cls) {
        Session session = HibernateSessionFactory.getSession();
        try {
            Criteria criteria = session.createCriteria(cls);
            List list = criteria.list();
            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.list();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null)
                session.close();
        }
        return null;
    }

    /**
     * 根据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;
    }      
    
    /**
     * 无参数的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添加语句
     * @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查询count语句
     * @param para Object[] 参数值数组
     * @return count值
     */
    public int selectCount(String sql,Object para[]){
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            SQLQuery query = session.createSQLQuery(sql);
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            Integer bigVal =(Integer)query.list().get(0);
            int val = bigVal.intValue();
            return val;
        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return 0;
    }
    
    
    /**
     * 带参查询的sql语句
     * @param sql
     * @param para
     * @return
     */
    public List selectSql(String sql,Object para[]){
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            SQLQuery query = session.createSQLQuery(sql);
            for (int i = 0; i < para.length; i++) {
                query.setParameter(i, para[i]);
            }
            List list =query.list();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /***
     * 无参查询的sql语句
     * @param sql
     * @return
     */
    public List selectSql(String sql){
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            SQLQuery query = session.createSQLQuery(sql);
            List list =query.list();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return null;
    }
    
    /**
     * 无参数的sql实现查询行数
     * @param sql sql查询count语句
     * @return count值
     */
    public int selectCount(String sql){
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启一个事务
            int count = (int) session.createSQLQuery(sql).uniqueResult();
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); // 撤销
            if (session != null)
                session.close();
        }
        return 0;
    }
    
    /**
     * 无参数查询表行数
     * @param cls 要查询的Hibernate的表映射类对象名
     * @return count值
     */
    public Long selectCount(Class cls){
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        Criteria criteria = session.createCriteria(cls);
        criteria.setProjection(Projections.rowCount());
        Long count = (Long) criteria.uniqueResult();
        return count;
    }
    
    /**
     * 无参数的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 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();
//            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;
    }
    
    /**
     * 有参数的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;
    }
    
    /**
     * 有参数的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;
    }

    /**
     * ResultSet转换为list
     * @param rs ResultSet
     * @return List
     * @throws SQLException
     */
    private List convertList(ResultSet rs) {
        List list = new ArrayList();
        try{
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                Map rowData = new HashMap();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                list.add(rowData);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
        return list;
    }
}

Junit Test

package JunitTest;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import basic.GsonUtil;
import basic.HibernateUtil;
import model.TBook;

public class HibernateUtilTest {
	HibernateUtil hib=new HibernateUtil();
	
	@Test
	public void testInsertList() {
		List<Object>list=new ArrayList<>();
		for (int i=0;i<500000;i++){ //50万数据测试
			TBook book=new TBook();
			book.setName("java"+i);
			book.setPrice("50");
			list.add(book);
		}
		long begin = System.currentTimeMillis(); 
		System.out.println(hib.insert(list));
		long end = System.currentTimeMillis(); 
		System.out.println((end-begin)/1000.0); 
	}
	
	@Test
	public void testInsertObject() {
		TBook book = new TBook();
		book.setName("java入门");
		book.setPrice("5");
		Object obj = hib.insert(book);
		System.out.println(obj);
	}

	@Test
	public void testDelete() {
		TBook deb = (TBook) hib.findById(TBook.class, 2);
		Object deo = hib.delete(deb);
		System.out.println(deo);
	}

	@Test
	public void testUpdate() {
		TBook upb = (TBook) hib.findById(TBook.class, 2);
		upb.setPrice("6");
		Object up = hib.update(upb);
		System.out.println(up);
	}

	@Test
	public void testSelectString() {
		 String hql="select new map(id as id) from TBook";
		 List list=hib.select(hql);
		 System.out.println(GsonUtil.ListToGson(list));
	}

	@Test
	public void testSelectClassOfT() {
		 List list=hib.select(TBook.class);
		 System.out.println(GsonUtil.ListToGson(list));
	}

	
	@Test
	public void testUpdateSql() {
		 String sql="UPDATE T_Book SET name = 'java' WHERE id = 1 ";
		 System.out.println(hib.update(sql));
	}

	@Test
	public void testUpdateSqlParam() {
		 String sql="UPDATE T_Book SET name = ? WHERE id = ? ";
		 Object[] ob={".net","1"};
		 System.out.println(hib.update(sql,ob));
	}
	
	@Test
	public void testInsertSql() {
		 String sql="INSERT INTO T_Book  VALUES ('sd', '2') ";
		 System.out.println(hib.insert(sql));
	}
	
	@Test
	public void testInsertSqlParam() {
		 String sql="INSERT INTO T_Book  VALUES (?, ?)";
		 Object[] ob={"jq","10"};
		 System.out.println(hib.insert(sql,ob));
	}
	
	@Test
	public void testDeleteSql() {
		 String sql="DELETE FROM T_Book WHERE id = 5 ";
		 System.out.println(hib.delete(sql));
	}
	
	@Test
	public void testDeleteSqlParam() {
		 String sql="DELETE FROM T_Book WHERE id = ? ";
		 Object[] ob={6};
		 System.out.println(hib.delete(sql,ob));
	}
	
	@Test
	public void testMulDeleteSql() {
		 String sql="DELETE FROM T_Book";
		 String identity="id";
		 String mulId="3,4";
		 System.out.println(hib.delete(sql,identity,mulId));
	}
	
	@Test
	public void testSelectSqlParam() {
		 String sql="FROM TBook WHERE id = ? ";
		 Object[] ob={1};
		 System.out.println(GsonUtil.ListToGson(hib.select(sql,ob)));
	}
	
	@Test
	public void testSelectCount() {
		 String sql="select count(*) FROM T_Book";
		 System.out.println(hib.selectCount(sql));
	}
	
	@Test
	public void testSelectCountParam() {
		 String sql="select count(*) FROM T_Book where id=?";
		 Object[] ob={1};
		 System.out.println(hib.selectCount(sql,ob));
	}
	
	@Test
	public void testSelectCountCri() {
		 System.out.println(hib.selectCount(TBook.class));
	}
}

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

不打赏,点击广告页面 也是对博主的打赏哦.ヘ( ̄ω ̄ヘ)

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



恰饭广告

发表评论

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

÷ 2 = 3