欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate Criteria 的用法 HibernateCC++C#F# 

程序员文章站 2024-01-24 07:59:58
...
Hibernate Criteria 的用法 1. 普通的查询 Criteria criteria = session.createCriteria(Track.class); criteria.add(Restrictions.le(”playTime”,length)); return criteria.list(); 2. 其他 Criteria criteria = session.createCriteria(Track.class); criteria.add(Restrictions.le(”playTime”,length)); criteria.addOrder(Order.asc(”title”).ignoreCase()); return criteria.list(); 3. 组合条件查询 Criteria critera = session.createCriteria(Track.class); criteria.add(Restrictions.le(”playTime”,length)); criteria.add(Restrictions.like(”title”,length)); criteria.addOrder(Order.asc(”title”).ignoreCase()); 4. 宽松条件查询(OR) session.createCriteria(Tarck.class) .add(Restrictions.disjunction() .add(Restrictions.le(”playTime”),length)) .add(Restrictions.like(”title”), “%A%”))) .addOrder(Order.asc(”title”).ignoreCase()) .list(); 5.对单一属性做简单投影,返回的List 是String类型的List对象 Session.createCriteria(Track.class) .add(Resritctions.like(”title”,”sometext”, MatchMOde.ANYWHERE).ignoreCase()) .setProjection(Projections.property(”title”)) .list(); 6.对多个属性做投影,返回Object数组类型的List对象 Session.createCriteria(Track.class) .add(Resritctions.like(”title”,”sometext”, MatchMOde.ANYWHERE).ignoreCase()) .setProjection(Projections.property(”title”)) .setProjection(Projections.property(”playTime”)) .list(); 7.带聚合的投影 a.创业一个ProjectionList实例 b.对sourceMedia字段分组 c.返回记录总数 d.返回分组的结果集中playTime的最大值 Session.createCriteria(Track.class) .setProjection(Projections.projectionList()) //a .add(Projections.groupProperty(”sourceMedia”)) //b .add(Projections.rowCount()) //c .add(Projections.max(”playTime”))); //d //select count(*), max(track.playTime) from track group by track.sourceMedia 8. 对聚合投影结果排序要通过设置别名来完成 Session.createCriteria(Track.class) .setProjection(Projections.projectionList()) .add(Projections.groupProperty(”sourceMedia”).as(”media”)) .add(Projections.rowCount()) .add(Projections.max(”playTime”))); .addOrder(Order.asc(”media”)); 9. 在关联中应用条件查询 Criteria criteria = session.createCriteria(Track.class); Criteria artistCriteria = criteria.createCriteria(”artists”); artistCritera.add(Restrictions.like(”name”,namePattern)); artisCriteria.addOrder(Order.asc(”name”).ignoreCase()); criteria.list(); 10. 示例查询 a.示例查询中,值为null的忽略 b.对字符串值按照区分大小写的逐字比较 c.如果比较时,需要忽略为0的属性,可以调用example.excludeZeroes() d.如果希望对值为null的属性进行匹配可以调用example.excludeNone() e.example.excludeProperty()用来明确忽略指定名称的特定属性 f.调整字符串处理,还可以使用ignoreCase()和enableLike()方法 SourceMedia media = new SourceMedia(); media.setName(”example”) Track track = new Track(); track.setSourceMedia(media); \\media 是一个SourceMedia对象 Example example = Example.create(track); Criteria criteria = session.createCriteria(Track.class); criteria.add(example); criteria.addOrder(Order.asc(”title”)); return critera.list();