Hibernate的查询方法sohu - 牛牛娱乐

Hibernate的查询方法sohu

2019-02-14 10:44:08 | 作者: 浩瀚 | 标签: 代码,目标,运用 | 浏览: 2435

1.运用主键id加载目标(load(),get());

2.经过目标导航,比方经过stu.getTeam()得到team的实例;

3.运用hql;

4.运用qbc(query by criteria)

5.直接运用sql句子获得记录集;

一般都运用后边三种办法.

留意.hql是面向目标的查询.语法和sql是根本相同的.不区别巨细写的,可是留意的是对与目标.有必要遵从目标的巨细写.由于hql是对像查询..一起咱们有必要清楚.hql只能获得目标,而不支持uid(update,insert.delete)

 

 

HQL功用最强壮,合适各种情况,可是动态条件查询结构起来很不便利 Criteria最合适动态条件查询,不太合适计算查询,QBE还不行强壮,只合适适当简略的查询 NativeSQL能够完成特定数据库的SQL,可是可移植性就献身了

Hibernate2的Criteria功用不行完善,所以Hibernate2上面可用的只要HQL和NativeSQL,Hibernate3的Criteria现已十分强壮了。

针对web运用来说,大部分惯例查询都是动态条件查询,所以首选运用Criteria,而且Hibernate3供给了DetachedCriteria,能够在web层结构好DetachedCriteria再进入session履行查询,十分便利有用的特性。

可是涉及到计算查询和十分复杂的相关查询,Criteria就力不从心了,这种情况下我挑选运用HQL。

 

 

 

以下是HQL/QBC/Native SQL三种查询战略 HQL战略:

Java代码 session.createQuery("FROM Category c where c.name like Laptop%"); 

session.createQuery("FROM Category c where c.name like Laptop%"); 

QBC战略:

Java代码 session.createCriteria(Category.class).add(Restrictions.like("name", "Laptop%")); 

session.createCriteria(Category.class).add(Restrictions.like("name", "Laptop%")); 

Native SQL战略

Java代码 session.createSQLQuery("select {c.*} from CATEGORY {c} where NAME like Laptop%").   addEntity("c",Category.class); 

session.createSQLQuery("select {c.*} from CATEGORY {c} where NAME like Laptop%"). addEntity("c",Category.class); 

节 8.02    分页查询

Java代码 Criteria criteria = session.createCriteria(Category.class)   .add(Restrictions.like("name", "Laptop%"));   criteria.addOrder(Order.asc("name"));   criteria.setFirstResult(0);//初始行数   criteria.setMaxResults(20);//每页显现行数 

Criteria criteria = session.createCriteria(Category.class) .add(Restrictions.like("name", "Laptop%")); criteria.addOrder(Order.asc("name")); criteria.setFirstResult(0);//初始行数 criteria.setMaxResults(20);//每页显现行数 

节 8.03    数据过滤 办法                      阐明    Restrictions.eq         =   Restrictions.allEq      使用Map来进行多个等于的约束    Restrictions.gt             Restrictions.ge         =    Restrictions.lt           Restrictions.le         =    Restrictions.between    BETWEEN   Restrictions.like       LIKE   Restrictions.in         in   Restrictions.and        and   Restrictions.or         or   Restrictions.sqlRestriction     用SQL约束查询 (a)    运用约束

Java代码 Criterion emailEq = Restrictions.eq("email", "w@163.com");   Criteria criteria = session.createCriteria(User.class);   criteria.add(emailEq);   User user = (User)criteria.uniqueResult(); 

Criterion emailEq = Restrictions.eq("email", "w@163.com"); Criteria criteria = session.createCriteria(User.class); criteria.add(emailEq); User user = (User)criteria.uniqueResult(); 

(b)    比较表达式

Java代码 Restrictions.between("amount", new BigDecimal(100), new BigDecimal(200));   Restrictions.gt("amount", new BigDecimal(100));   Restrictions.in("email", emails);//注:emails为调集   Restrictions.isNull("email");   Restrictions.isNotNull("email");   Restrictions.isEmpty("bids");   Restrictions.sizeGe("bids", 3);//bids特点巨细 

Restrictions.between("amount", new BigDecimal(100), new BigDecimal(200)); Restrictions.gt("amount", new BigDecimal(100)); Restrictions.in("email", emails);//注:emails为调集 Restrictions.isNull("email"); Restrictions.isNotNull("email"); Restrictions.isEmpty("bids"); Restrictions.sizeGe("bids", 3);//bids特点巨细 

(c)    字符串匹配

Java代码 Restrictions.like("email", "G%");   Restrictions.like("email", "G%",MatchMode.START);   注:MatchMode分为START,END,ANYWHERE,EXACT四种形式   Restrictions.like("email", "G%").ignoreCase(); 

Restrictions.like("email", "G%"); Restrictions.like("email", "G%",MatchMode.START); 注:MatchMode分为START,END,ANYWHERE,EXACT四种形式 Restrictions.like("email", "G%").ignoreCase(); 

(d)    组合表达式和逻辑操作符

Java代码 Restrictions.or(                   Restrictions.and(                           Restrictions.like("firstname", "G%"),                           Restrictions.like("lastname", "K%")),                           Restrictions.in("email",emails)); 

Restrictions.or(                 Restrictions.and(                         Restrictions.like("firstname", "G%"),                         Restrictions.like("lastname", "K%")),                         Restrictions.in("email",emails)); 

(e)    SQL表达式

Java代码 Restrictions.sqlRestriction("{alias}.name=tie and {alias}.addr=dalian");   Restrictions.sqlRestriction("{alias}.name=?",  "tie", Hibernate.STRING);//姓名为tie的目标   Restrictions.sqlRestriction("length({alias}.PASSWORD) ?",5,Hibernate.INTEGER);   //暗码小于5个字符目标   Restrictions.sqlRestriction("100 all( select b.AMOUNT FROM BID b " +                   " WHERE b.ITEM_ID = {alias}.ITEM_ID)");//回来出价不大于100 

Restrictions.sqlRestriction("{alias}.name=tie and {alias}.addr=dalian"); Restrictions.sqlRestriction("{alias}.name=?",  "tie", Hibernate.STRING);//姓名为tie的目标 Restrictions.sqlRestriction("length({alias}.PASSWORD) ?",5,Hibernate.INTEGER); //暗码小于5个字符目标 Restrictions.sqlRestriction("100 all( select b.AMOUNT FROM BID b " +                 " WHERE b.ITEM_ID = {alias}.ITEM_ID)");//回来出价不大于100 


(f)    子查询

节 8.04    表相关 (a)    隐式相关 隐式相关有两种办法: 1、    Criteria接口的createCriteria()办法:

Java代码 session.createCriteria(Item.class)   .add(Restrictions.like("description", "Foo",MatchMode.ANYWHERE))   .createCriteria("bids")   .add(Restrictions.gt("amount",new BigDecimal(100)));   session.createCriteria(Item.class)               .createCriteria("seller")               .add(Restrictions.like("email", "%@")); 

session.createCriteria(Item.class) .add(Restrictions.like("description", "Foo",MatchMode.ANYWHERE)) .createCriteria("bids") .add(Restrictions.gt("amount",new BigDecimal(100)));

session.createCriteria(Item.class)             .createCriteria("seller")             .add(Restrictions.like("email", "%@")); 

2、    分配别号:

Java代码 session.createCriteria(Item.class)               .createAlias("bids","b")               .add(Restrictions.like("description", "%Foo%"))               .add(Restrictions.gt("b.amount", new BigDecimal(100)));   session.createCriteria(Item.class)               .createAlias("seller", "s")               .add(Restrictions.like("s.email","%@")); 

session.createCriteria(Item.class)             .createAlias("bids","b")             .add(Restrictions.like("description", "%Foo%"))             .add(Restrictions.gt("b.amount", new BigDecimal(100)));

session.createCriteria(Item.class)             .createAlias("seller", "s")             .add(Restrictions.like("s.email","%@")); 

(b)    抓取相关

Java代码 session.createCriteria(Item.class)               .setFetchMode("bids",FetchMode.JOIN)               .add(Restrictions.like("description", "%Foo%")) 

session.createCriteria(Item.class)             .setFetchMode("bids",FetchMode.JOIN)             .add(Restrictions.like("description", "%Foo%")) 



节 8.05    投影/报表查询 (a)    简略投影

Java代码 session.createCriteria(Item.class)           .add(Restrictions.gt("endDate", new Date()))           .setProjection(Projections.id());//回来单一特点   session.createCriteria(Item.class).setProjection(   Projections.projectionList().add(Projections.id()).   add(Projections.property("description")));//回来一个Object[] 

session.createCriteria(Item.class)         .add(Restrictions.gt("endDate", new Date()))         .setProjection(Projections.id());//回来单一特点

session.createCriteria(Item.class).setProjection( Projections.projectionList().add(Projections.id()). add(Projections.property("description")));//回来一个Object[] 


(b)    计算分组

Java代码 session.createCriteria(Item.class)   .setProjection(Projections.rowCount());   session.createCriteria(Item.class)               .setProjection(Projections.projectionList()               .add(Projections.rowCount())               .add(Projections.sum("sales"))               .add(Projections.avg("score"))               );       session.createCriteria(Bid.class)           .createAlias("bidder", "u")           .setProjection(Projections.projectionList()                   .add(Property.forName("u.id").group())                   .add(Property.forName("u.username").group())                   .add(Property.forName("id").count())                   .add(Property.forName("amount").avg())               ); 

session.createCriteria(Item.class) .setProjection(Projections.rowCount());

session.createCriteria(Item.class)             .setProjection(Projections.projectionList()             .add(Projections.rowCount())             .add(Projections.sum("sales"))             .add(Projections.avg("score"))             );

    session.createCriteria(Bid.class)         .createAlias("bidder", "u")         .setProjection(Projections.projectionList()                 .add(Property.forName("u.id").group())                 .add(Property.forName("u.username").group())                 .add(Property.forName("id").count())                 .add(Property.forName("amount").avg())             ); 



(c)    SQL投影

Java代码 String sqlFragment = "(select count(*) from Item i where i.item_id = item_id) "                  + " as numofitems";           session.createCriteria(Bid.class).createAlias("bidder", "u")                   .setProjection(                           Projections.projectionList().add(                                   Projections.groupProperty("u.id")).add(                                   Projections.groupProperty("u.username")).add(                                   Projections.count("id")).add(                                   Projections.avg("amount")).add(                                   Projections.sqlProjection(sqlFragment,                                           new String[] { "numofitems" },                                           new Type[] { Hibernate.LONG }))                   );

版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表牛牛娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章