`
周一Monday
  • 浏览: 348617 次
  • 来自: 北京
社区版块
存档分类
最新评论

Hibernate的批量处理

阅读更多
package org.monday.app;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.monday.domain.User;
import org.monday.util.HibernateUtil;

public class UserManager {

	public static void main(String[] args) {
		// batchInsert();
		// batchUpdate();
		batchDelete();
	}

	/**
	 * 批量添加
	 */
	public static void batchInsert() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		for (int i = 1,n=10000; i <= n; i++) {
			User u = new User();
			u.setName("sql" + i);
			session.save(u); 	 // save

			if (i % 20 == 0) {
				session.flush(); // 将Session缓存的数据写入到数据库
				session.clear(); // 手动清空Session缓存
			}
		}
		tx.commit();
		HibernateUtil.closeSession();
		System.out.println("ok");
		
		/**
		 * <!-- 关闭Hibernate的二级缓存 -->
		   <property name="hibernate.cache.use_second_level_cache">false</property>
		      除了Session的缓存要关闭外,最好将SessionFactory的二级缓存也关闭了
		 */
	}

	/**
	 * 批量更新
	 */
	public static void batchUpdate() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = "update User set name = ? where id<=?";
		int count = session.createQuery(hql).setParameter(0, "hql").setParameter(1, 10).executeUpdate();
		tx.commit();
		HibernateUtil.closeSession();
		System.out.println("update:" + count);
	}

	/**
	 * 批量删除
	 */
	public static void batchDelete() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = "delete from User where id<=?";
		int count = session.createQuery(hql).setParameter(0, 10).executeUpdate();
		tx.commit();
		HibernateUtil.closeSession();
		System.out.println("delete:" + count);
	}
}

 

package org.monday.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	/** 声明SessionFactory对象 */
	private static final SessionFactory sf;

	/**
	 * 静态块创建SessionFactory对象
	 */
	static {
		try {
			Configuration cfg = new Configuration().configure();
			sf = cfg.buildSessionFactory();
		} catch (Throwable e) {
			System.out.println("创建SessionFactory失败");
			throw new ExceptionInInitializerError(e);
		}
	}

	/** 声明ThreadLocal对象绑定Session */
	private static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	/**
	 * 获取Session
	 * 
	 * @return 当前邦定到ThreadLocal的Session
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		Session s = session.get();
		if (s == null) {
			s = sf.openSession();
			session.set(s);
		}
		return s;
	}

	/**
	 * 关闭Session
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		Session s = session.get();
		if (s != null) {
			s.close();
		}
		session.set(null);
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics