Hibernate查询——hql,Criteria,标准sql

1. HQL(Hibernate Query Language)是hibernate专门用于查询数据的语句。

有别于sql,hql更接近于面向对象的思维方式。使用HQL,根据name进行模糊查询。假设有一个数据库表叫product_,对应的实体类名为Product。现在要查询产品类名中含有”abc“的产品。

  1. 首先根据hql创建一个Query对象。
  2. 设置参数(Query是基0的,PreparedStatement是基1的)
  3. 通过Query对象的list()方法即返回查询的结果。
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String name = "abc";
Query q = s.createQuery("from Product p where p.name like ?");
q.setString(0,"%"+name+"%");
List<Product> ps = q.list();
for(Product p :ps){
    System.out.println(p.getName());
}

s.getTransaction().commit();
s.close();
sf.close();

2. 使用Criteria进行数据查询。

与HQL,SQL的区别是Criteria完全是面向对象的方式在进行数据查询,将不再看到有sql语句的痕迹。

使用Criteria查询数据:

  1. 通过session的createCriteria创建一个Criteria对象。
  2. Criteria.add增加约束(本例中增加一个对name的模糊查询(like))。
  3. 调用list()方法返回查询结果的集合。

除此之外,Criteria还可以很方便的进行分页查询和获取总数。

SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String name = "abc";
Criteria c = s.createCriteria(Product.class);
c.add(Restrictions.like("name","%"+name+"%"));
List<Product> ps = c.list();
for(Product p:ps){
    System.out.println(p.getName());
}

s.getTransaction().commit();
s.close();
sf.close();

3. 使用标准SQL,根据name进行模糊查询。

使用Session的createSQLQuery方法执行标准sql语句。因为标准sql语句有可能返回各种各样的结果,比如多表查询,分组统计结果等等。不能保证其查询结果能够装进一个Product对象中,所以返回的集合里的每一个元素是一个对象数组,然后再通过下标把这个对象数组中的数据取出来。

SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String name = "abc";

String sql = "select * from product_ p where p.name like '%"+name+"%'";
Query q = s.createSQLQuery(sql);
List<Object[]> list = q.list();
for(Object[] os :list){
    for(Object field:os){
        System.out.println(field+"\t");
    }
    System.out.println();
}

s.getTransaction().commit();
s.close();
sf.close();
发布了25 篇原创文章 · 获赞 1 · 访问量 7526

猜你喜欢

转载自blog.csdn.net/qq_28334237/article/details/86549631