Hibernate的HQL查询和工具类的增强
来源:互联网 发布:狼友基地最新最全数据 编辑:程序博客网 时间:2024/06/06 00:34
其实对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();}}}
- Hibernate的HQL查询和工具类的增强
- Hibernate的Hql查询
- hibernate的HQL查询
- Hibernate的HQL查询
- hibernate的hql查询
- Hibernate的HQL查询
- Hibernate的HQL查询
- hibernate的HQL查询
- Hibernate的HQL查询
- [Hibernate]Hibernate的HQL查询
- Hibernate的查询 HQL查询
- Hibernate 中 HQL查询 和SQL查询的区别
- hibernate原生sql查询和hql查询的注意点
- Hibernate HQL的子查询
- hibernate hql不支持的查询
- 关于Hibernate的HQL查询
- hibernate的HQL查询语言
- hibernate的hql查询语句
- JVM优化之逃逸分析(Escape Analysis)
- 程序运行时,利用反射调用不同窗体
- 没有域环境下安装SharePoint 2010
- 应用程序的重定向
- 02/28
- Hibernate的HQL查询和工具类的增强
- csdn博客bug测试
- 八零后为什么比我们那时还艰难
- 分享功能
- IEEE参考文献格式
- 关于虚拟地址空间
- 【linux】ubuntu11.10下各种问题以及解决方案
- 有关游戏的部署方案总结
- 修改图片上的文字步骤