Hibernate的HQL查询和工具类的增强

其实对Hibernate进行分析后可以发现,这个Hibernate对于对象的增加。删除,更新是差不多的,所以可以把他们整

合到一个工具类中去。还有就是,因为查询是很复杂的,所以对于数据库的查询,就有相对应的接口,类似于JDBC中

的PreparedStatemented这个类。下面我们先看一下工具类的增强

package com.bird.hibernate.test;

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

@SuppressWarnings("deprecation")
public final class Hibernateutils {
	
	private static SessionFactory sf;
	
	private Hibernateutils(){}
	
	static{
		Configuration cfg = new Configuration();
		cfg.configure();
		sf = cfg.buildSessionFactory();
	}

	public static SessionFactory getSessionFactory() {
		return sf;
	}
	
	public static Session getSession(){
		return sf.openSession();
	}
	
	public static void add(Object entity){
		Session s = null;
		Transaction ts = null;

		try {
			s = sf.openSession();
			ts = s.beginTransaction();
			s.save(entity);
			ts.commit();
		} catch (HibernateException e) {
			if (ts != null)
				ts.rollback();
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
	
	public static void update(Object entity){
		Session s = null;
		Transaction ts = null;

		try {
			s = sf.openSession();
			ts = s.beginTransaction();
			s.update(entity);
			ts.commit();
		} catch (HibernateException e) {
			if (ts != null)
				ts.rollback();
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
	
	
	public static void delete(Object entity){
		Session s = null;
		Transaction ts = null;

		try {
			s = sf.openSession();
			ts = s.beginTransaction();
			s.delete(entity);
			ts.commit();
		} catch (HibernateException e) {
			if (ts != null)
				ts.rollback();
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
}

然后是查询,使用hql是只面向对象的,不考虑什么表的问题。其他的和jdbc类是

package com.bird.hibernate.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.bird.domain.User;

public class QueryTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		query("bird");

	}
	
	
	public static void query(String name){
		Session s = null;
		
		try {
			s = Hibernateutils.getSession();
			String hql="from User as use where use.name=?";
			Query query = s.createQuery(hql);
			query.setString(0, name);
			
			
			@SuppressWarnings("unchecked")
			List<Object> list = query.list();
			
			for(Object o: list){
				System.out.println(((User)o).getName());
			}
		
		} catch (HibernateException e) {
			
			throw e;
		} finally {
			if (s != null)
				s.close();
		}
	}
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值