首页 > 代码库 > Criterion & DetachedCriteria
Criterion & DetachedCriteria
今天笔记主要是记录笔记,以及代码:
criteria:
创建查询接口:createCriteria(class)
查询条件接口:add(各种条件);
Restrictions 提供了设置参数的各种接口
逻辑运算 not or and
字符串模式匹配 like ilike
范围运算 in not in between between and
比较运算 eq/le/lt.....
集合运算 isNotEmpty
可以链式编程
List grades=session.createCriteria(Grade.class)
.add(Restrictions.or(Restrictions.eq("gradename", "一年级"), Restrictions.le("gradeid", 3)))
.list();
关于各种方法的使用,代码中都有注释
注解配置:
可以在启动AnnotationConfiguration时在数据库创建配置的表
注解:
需要引入四个包:
1 package entity; 2 import java.io.Serializable; 3 import javax.persistence.*; 4 5 @Entity 6 @Table(name="test_g") 7 public class TestNoteGrade implements Serializable{ 8 private Integer id ; 9 private String name;10 @Id11 @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_grade")12 @SequenceGenerator(name="seq_grade",sequenceName="seq_gradeid",allocationSize=1,initialValue=http://www.mamicode.com/1)13 public Integer getId() {14 return id;15 }16 17 public void setId(Integer id) {18 this.id = id;19 }20 @Basic21 public String getName() {22 return name;23 }24 public void setName(String name) {25 this.name = name;26 }27 28 29 30 31 }
在hibernate中需要配置 mapping:
<mapping class="entity.TestNoteGrade"/>
还有种生成实体类与映射文件的方法:
反推(用myeclipse来操作)
java 测试代码:
1 package test4Criteria; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.Set; 6 7 import junit.framework.TestCase; 8 import org.hibernate.Criteria; 9 import org.hibernate.Session; 10 import org.hibernate.cfg.AnnotationConfiguration; 11 import org.hibernate.criterion.Criterion; 12 import org.hibernate.criterion.DetachedCriteria; 13 import org.hibernate.criterion.Order; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 18 import entity.Grade; 19 import entity.Student; 20 import entity.TrStudent; 21 22 import util.HibernateUtil; 23 24 public class Criterion01 extends TestCase{ 25 Session session=null; 26 27 28 29 /** 30 * critertion 查询 31 */ 32 public void testCriterion1(){ 33 try { 34 session=HibernateUtil.currentSession(); 35 session.beginTransaction(); 36 //查询整个类 37 List grade=session.createCriteria(Grade.class).list(); 38 for(int i=0;i<grade.size();i++){ 39 Grade gra=(Grade)grade.get(i); 40 System.out.println(gra); 41 42 } 43 44 45 } catch (Exception e) { 46 // TODO: handle exception 47 e.printStackTrace(); 48 }finally{ 49 HibernateUtil.closeSession(); 50 } 51 try { 52 session=HibernateUtil.currentSession(); 53 session.beginTransaction(); 54 //查询指定值 55 List grade=session.createCriteria(Grade.class)// 56 .add(Restrictions.eq("gradename","一年级"))// 57 .list(); 58 for(int i=0;i<grade.size();i++){ 59 Grade gra=(Grade)grade.get(i); 60 System.out.println(gra); 61 62 } 63 64 65 } catch (Exception e) { 66 // TODO: handle exception 67 e.printStackTrace(); 68 }finally{ 69 HibernateUtil.closeSession(); 70 } 71 72 } 73 /** 74 * 比较运算 75 */ 76 public void testCriterion2(){ 77 try { 78 session=HibernateUtil.currentSession(); 79 session.beginTransaction(); 80 //大于条件 81 List grades=session.createCriteria(Grade.class).add(Restrictions.gt("gradeid", 2)).list(); 82 83 for(int i=0;i<grades.size();i++){ 84 System.out.println((Grade)grades.get(i)); 85 86 } 87 } catch (Exception e) { 88 // TODO: handle exception 89 e.printStackTrace(); 90 }finally{ 91 HibernateUtil.closeSession(); 92 93 } 94 System.out.println("---大于等于条件--------------------"); 95 try { 96 session=HibernateUtil.currentSession(); 97 session.beginTransaction(); 98 //大于等于条件 99 List grades=session.createCriteria(Grade.class).add(Restrictions.ge("gradeid", 2)).list();100 101 for(int i=0;i<grades.size();i++){102 System.out.println((Grade)grades.get(i));103 104 }105 } catch (Exception e) {106 // TODO: handle exception107 e.printStackTrace();108 }finally{109 HibernateUtil.closeSession();110 111 }112 113 System.out.println("---小于等于条件--------------------");114 try {115 session=HibernateUtil.currentSession();116 session.beginTransaction();117 //大于等于条件118 List grades=session.createCriteria(Grade.class).add(Restrictions.le("gradeid", 2)).list();119 120 for(int i=0;i<grades.size();i++){121 System.out.println((Grade)grades.get(i));122 123 }124 } catch (Exception e) {125 // TODO: handle exception126 e.printStackTrace();127 }finally{128 HibernateUtil.closeSession();129 130 }131 System.out.println("---等于空--------------------");132 try {133 session=HibernateUtil.currentSession();134 session.beginTransaction();135 //大于等于条件136 List grades=session.createCriteria(Grade.class).add(Restrictions.isNull("gradeid")).list();137 138 for(int i=0;i<grades.size();i++){139 System.out.println((Grade)grades.get(i));140 141 }142 } catch (Exception e) {143 // TODO: handle exception144 e.printStackTrace();145 }finally{146 HibernateUtil.closeSession();147 148 }149 150 }151 /**152 * 范围运算153 */154 public void testCriterion3(){155 try {156 session=HibernateUtil.currentSession();157 session.beginTransaction();158 Object[] obj={1,2,3};159 //in160 List grades=session.createCriteria(Grade.class)//161 .add(Restrictions.in("gradeid",obj))//162 .list();163 for(int i=0;i<grades.size();i++){164 System.out.println((Grade)grades.get(i));165 166 }167 } catch (Exception e) {168 // TODO: handle exception169 e.printStackTrace();170 }171 finally{172 HibernateUtil.closeSession();173 174 }175 System.out.println("-----not--in------");176 try {177 session=HibernateUtil.currentSession();178 session.beginTransaction();179 Object[] obj={1,2,3};180 //in181 List grades=session.createCriteria(Grade.class)//182 .add(Restrictions.not(Restrictions.in("gradeid",obj)))//183 .list();184 for(int i=0;i<grades.size();i++){185 System.out.println((Grade)grades.get(i));186 187 }188 } catch (Exception e) {189 // TODO: handle exception190 e.printStackTrace();191 }192 finally{193 HibernateUtil.closeSession();194 195 }196 197 System.out.println("--not-between- and--");198 try {199 session=HibernateUtil.currentSession();200 session.beginTransaction();201 Object[] obj={1,2,3};202 //in203 List grades=session.createCriteria(Grade.class)//204 .add(Restrictions.not(Restrictions.between("gradeid",1,3)))//205 .list();206 for(int i=0;i<grades.size();i++){207 System.out.println((Grade)grades.get(i));208 209 }210 } catch (Exception e) {211 // TODO: handle exception212 e.printStackTrace();213 }214 finally{215 HibernateUtil.closeSession();216 217 }218 219 System.out.println("---between- and--");220 try {221 session=HibernateUtil.currentSession();222 session.beginTransaction();223 Object[] obj={1,2,3};224 //in225 List grades=session.createCriteria(Grade.class)//226 .add(Restrictions.between("gradeid",1,3))//227 .list();228 for(int i=0;i<grades.size();i++){229 System.out.println((Grade)grades.get(i));230 231 }232 } catch (Exception e) {233 // TODO: handle exception234 e.printStackTrace();235 }236 finally{237 HibernateUtil.closeSession();238 239 }240 }241 242 /**243 * 字符串模式匹配 like ilike 244 */245 public void testCriterion4(){246 try {247 session=HibernateUtil.currentSession();248 session.beginTransaction();249 String scase="ab";250 List student=session.createCriteria(Student.class).add(Restrictions.like("name", "%"+scase+"%")).list();251 for(int i=0;i<student.size();i++){252 Student stu=(Student)student.get(i);253 String name=stu.getName();254 System.out.print(name.substring(0, name.indexOf(scase)));255 System.err.print(name.substring(name.indexOf(scase),(name.indexOf(scase)+scase.length())));256 if(name.indexOf(scase)==name.length()-scase.length()){257 System.out.println("");258 259 }260 System.out.println(name.substring(name.indexOf(scase)+scase.length(),name.length()));261 262 }263 264 } catch (Exception e) {265 // TODO: handle exception266 }finally{267 HibernateUtil.closeSession();268 269 }270 System.out.println("------ilike----------");271 try {272 session=HibernateUtil.currentSession();273 session.beginTransaction();274 String scase="eli";275 List student=session.createCriteria(Student.class).add(Restrictions.ilike("name", "%"+scase+"%")).list();276 for(int i=0;i<student.size();i++){277 Student stu=(Student)student.get(i);278 String name=stu.getName().toLowerCase();279 System.out.print(name.substring(0, name.indexOf(scase)));280 System.err.print(name.substring(name.indexOf(scase),(name.indexOf(scase)+scase.length())));281 if(name.indexOf(scase)==name.length()-scase.length()){282 System.out.println("");283 284 }285 System.out.println(name.substring(name.indexOf(scase)+scase.length(),name.length()));286 287 }288 } catch (Exception e) {289 // TODO: handle exception290 }finally{291 HibernateUtil.closeSession();292 293 }294 }295 /**296 * 逻辑运算297 */298 public void testCriterion5(){299 try {300 session=HibernateUtil.currentSession();301 session.beginTransaction();302 List grades=session.createCriteria(Grade.class).add(Restrictions.and(Restrictions.eq("gradename", "一年级"), Restrictions.le("gradeid", 5))).list();303 for(int i=0;i<grades.size();i++){304 System.out.println(grades.get(i));305 306 }307 } catch (Exception e) {308 // TODO: handle exception309 e.printStackTrace();310 }finally{311 HibernateUtil.closeSession();312 313 }314 System.out.println("-------or-----------");315 try {316 session=HibernateUtil.currentSession();317 session.beginTransaction();318 List grades=session.createCriteria(Grade.class).add(Restrictions.or(Restrictions.eq("gradename", "一年级"), Restrictions.le("gradeid", 3))).list();319 for(int i=0;i<grades.size();i++){320 System.out.println(grades.get(i));321 322 }323 } catch (Exception e) {324 // TODO: handle exception325 e.printStackTrace();326 }finally{327 HibernateUtil.closeSession();328 329 }330 System.out.println("-------not-----------");331 try {332 session=HibernateUtil.currentSession();333 session.beginTransaction();334 List grades=session.createCriteria(Grade.class).add(Restrictions.not(Restrictions.eq("gradename", "一年级"))).list();335 for(int i=0;i<grades.size();i++){336 System.out.println(grades.get(i));337 338 }339 } catch (Exception e) {340 // TODO: handle exception341 e.printStackTrace();342 }finally{343 HibernateUtil.closeSession();344 345 }346 347 }348 /**349 * 集合运算350 */351 public void testCriterion6(){352 try {353 session=HibernateUtil.currentSession();354 session.beginTransaction();355 List grades=session.createCriteria(Grade.class).add(Restrictions.isNotEmpty("stu")).list();356 for(int i=0;i<grades.size();i++){357 System.out.println(((Grade)grades.get(i)).getStu());358 }359 360 361 } catch (Exception e) {362 // TODO: handle exception363 e.printStackTrace();364 }finally{365 HibernateUtil.closeSession();366 367 }368 }369 370 /**371 * 动态查询372 */373 public void testTrends(){374 try {375 session=HibernateUtil.currentSession();376 session.beginTransaction();377 TrStudent tr=new TrStudent();378 tr.setName("%eli%");379 tr.setStartGrade(1);380 tr.setEndGrade(3);381 Criteria cri= session.createCriteria(Student.class);382 if(tr.getName()!=null){383 cri.add(Restrictions.like("name", tr.getName()));384 }if(tr.getStartGrade()!=null&&tr.getEndGrade()!=null){385 cri.add(Restrictions.between("gradeid",tr.getStartGrade(),tr.getEndGrade()));386 387 }if(tr.getStartGrade()!=null&&tr.getEndGrade()==null){388 cri.add(Restrictions.ge("gradeid",tr.getStartGrade()));389 390 }391 if(tr.getStartGrade()==null&&tr.getEndGrade()!=null){392 cri.add(Restrictions.le("gradeid",tr.getEndGrade()));393 394 }395 List student=cri.addOrder(Order.asc("gradeid")).setMaxResults(80).list();396 //根据年级排序,每页显示十条397 Integer pagesize=10;398 Integer page=1;399 System.out.println(student.size()/pagesize);400 for(int i=0;i<student.size()/pagesize;i++){401 System.out.println("--------第 "+page+" 页-------------");402 List students=cri.addOrder(Order.asc("gradeid")).setFirstResult(pagesize*(page-1)).setMaxResults(pagesize).list();403 page++;404 for(int j=0;j<students.size();j++){405 System.out.println(students.get(j));406 }407 System.out.println(page);408 409 410 411 }412 413 414 } catch (Exception e) {415 // TODO: handle exception416 e.printStackTrace();417 }finally{418 HibernateUtil.closeSession();419 }420 421 422 }423 /**424 * 链接查询425 */426 public void testrelevance(){427 try {428 session=HibernateUtil.currentSession();429 session.beginTransaction();430 List student=session.createCriteria(Student.class).createCriteria("grade").addOrder(Order.asc("gradeid")).setMaxResults(20).list();431 for(int i=0;i<student.size();i++){432 System.out.println(student.get(i)+"\t"+((Student)student.get(i)).getGrade().getGradename());433 }434 435 436 437 } catch (Exception e) {438 // TODO: handle exception439 e.printStackTrace();440 }finally{441 HibernateUtil.closeSession();442 }443 System.out.println("---createAlias()查询---");444 try {445 session=HibernateUtil.currentSession();446 session.beginTransaction();447 List student=session.createCriteria(Student.class,"s").createAlias("grade","g").addOrder(Order.asc("s.gradeid")).setMaxResults(20).list();448 for(int i=0;i<student.size();i++){449 System.out.println(student.get(i)+"\t"+((Student)student.get(i)).getGrade().getGradename());450 }451 452 } catch (Exception e) {453 // TODO: handle exception454 e.printStackTrace();455 }finally{456 HibernateUtil.closeSession();457 }458 }459 460 /**461 * 投影查询462 */463 public void testProj(){464 System.out.println("--查询记录总数--");465 try {466 session=HibernateUtil.currentSession();467 session.beginTransaction();468 //查询所有年级名称469 Object obj=session.createCriteria(Grade.class)470 .setProjection(Projections.projectionList().add(Projections.rowCount()))471 .list();472 System.out.println("所有班级:"+obj);473 474 } catch (Exception e) {475 // TODO: handle exception476 e.printStackTrace();477 }finally{478 HibernateUtil.closeSession();479 }480 481 System.out.println("--查询班级名称--");482 try {483 session=HibernateUtil.currentSession();484 session.beginTransaction();485 //查询所有年级名称486 Object obj=session.createCriteria(Grade.class)487 .setProjection(Projections.projectionList().add(Property.forName("gradename")))488 .list();489 System.out.println(obj);490 491 } catch (Exception e) {492 // TODO: handle exception493 e.printStackTrace();494 }finally{495 HibernateUtil.closeSession();496 }497 }498 499 /**500 * DetachedCriteria 离线查询501 */502 public void testoff_line(){503 try {504 //这段代码一般放在web产生查询条件505 DetachedCriteria det=DetachedCriteria.forClass(Student.class,"s")506 .createAlias("s.grade", "g")507 .add(Restrictions.eq("g.gradename", "幼儿园"));508 509 //数据访问层510 session=HibernateUtil.currentSession();511 session.beginTransaction();512 List students=det.getExecutableCriteria(session).add(Restrictions.ilike("s.name","%yap%")).setMaxResults(50).list();513 //打印514 for(int i=0;i<students.size();i++){515 System.out.println(students.get(i)+"\t"+((Student)students.get(i)).getGrade().getGradename());516 }517 518 } catch (Exception e) {519 // TODO: handle exception520 e.printStackTrace();521 }finally{522 HibernateUtil.closeSession();523 524 }525 }526 /**注解 的效果527 * 启动时会在数据库创建一个表528 */529 public void testNote(){530 try {531 AnnotationConfiguration anc=new AnnotationConfiguration().configure();532 session=anc.buildSessionFactory().openSession();533 session.beginTransaction();534 session.getTransaction().commit();535 } catch (Exception e) {536 // TODO: handle exception537 e.printStackTrace();538 session.getTransaction().rollback();539 }finally{540 session.close();541 }542 543 }544 545 546 547 548 549 550 }
Criterion & DetachedCriteria
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。