今天笔记主要是记录笔记,以及代码: 

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时在数据库创建配置的表

注解:

 需要引入四个包:

   

 package entity;
import java.io.Serializable;
import javax.persistence.*; @Entity
@Table(name="test_g")
public class TestNoteGrade implements Serializable{
private Integer id ;
private String name;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_grade")
@SequenceGenerator(name="seq_grade",sequenceName="seq_gradeid",allocationSize=1,initialValue=1)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
}
@Basic
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }

  在hibernate中需要配置 mapping:

    <mapping class="entity.TestNoteGrade"/>

  还有种生成实体类与映射文件的方法:

    反推(用myeclipse来操作)

java 测试代码:

 package test4Criteria;

 import java.util.ArrayList;
import java.util.List;
import java.util.Set; import junit.framework.TestCase;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions; import entity.Grade;
import entity.Student;
import entity.TrStudent; import util.HibernateUtil; public class Criterion01 extends TestCase{
Session session=null; /**
* critertion 查询
*/
public void testCriterion1(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//查询整个类
List grade=session.createCriteria(Grade.class).list();
for(int i=0;i<grade.size();i++){
Grade gra=(Grade)grade.get(i);
System.out.println(gra); } } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//查询指定值
List grade=session.createCriteria(Grade.class)//
.add(Restrictions.eq("gradename","一年级"))//
.list();
for(int i=0;i<grade.size();i++){
Grade gra=(Grade)grade.get(i);
System.out.println(gra); } } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
} }
/**
* 比较运算
*/
public void testCriterion2(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//大于条件
List grades=session.createCriteria(Grade.class).add(Restrictions.gt("gradeid", 2)).list(); for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
System.out.println("---大于等于条件--------------------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//大于等于条件
List grades=session.createCriteria(Grade.class).add(Restrictions.ge("gradeid", 2)).list(); for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); } System.out.println("---小于等于条件--------------------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//大于等于条件
List grades=session.createCriteria(Grade.class).add(Restrictions.le("gradeid", 2)).list(); for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
System.out.println("---等于空--------------------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//大于等于条件
List grades=session.createCriteria(Grade.class).add(Restrictions.isNull("gradeid")).list(); for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); } }
/**
* 范围运算
*/
public void testCriterion3(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
Object[] obj={1,2,3};
//in
List grades=session.createCriteria(Grade.class)//
.add(Restrictions.in("gradeid",obj))//
.list();
for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
HibernateUtil.closeSession(); }
System.out.println("-----not--in------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
Object[] obj={1,2,3};
//in
List grades=session.createCriteria(Grade.class)//
.add(Restrictions.not(Restrictions.in("gradeid",obj)))//
.list();
for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
HibernateUtil.closeSession(); } System.out.println("--not-between- and--");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
Object[] obj={1,2,3};
//in
List grades=session.createCriteria(Grade.class)//
.add(Restrictions.not(Restrictions.between("gradeid",1,3)))//
.list();
for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
HibernateUtil.closeSession(); } System.out.println("---between- and--");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
Object[] obj={1,2,3};
//in
List grades=session.createCriteria(Grade.class)//
.add(Restrictions.between("gradeid",1,3))//
.list();
for(int i=0;i<grades.size();i++){
System.out.println((Grade)grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
HibernateUtil.closeSession(); }
} /**
* 字符串模式匹配 like ilike
*/
public void testCriterion4(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
String scase="ab";
List student=session.createCriteria(Student.class).add(Restrictions.like("name", "%"+scase+"%")).list();
for(int i=0;i<student.size();i++){
Student stu=(Student)student.get(i);
String name=stu.getName();
System.out.print(name.substring(0, name.indexOf(scase)));
System.err.print(name.substring(name.indexOf(scase),(name.indexOf(scase)+scase.length())));
if(name.indexOf(scase)==name.length()-scase.length()){
System.out.println(""); }
System.out.println(name.substring(name.indexOf(scase)+scase.length(),name.length())); } } catch (Exception e) {
// TODO: handle exception
}finally{
HibernateUtil.closeSession(); }
System.out.println("------ilike----------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
String scase="eli";
List student=session.createCriteria(Student.class).add(Restrictions.ilike("name", "%"+scase+"%")).list();
for(int i=0;i<student.size();i++){
Student stu=(Student)student.get(i);
String name=stu.getName().toLowerCase();
System.out.print(name.substring(0, name.indexOf(scase)));
System.err.print(name.substring(name.indexOf(scase),(name.indexOf(scase)+scase.length())));
if(name.indexOf(scase)==name.length()-scase.length()){
System.out.println(""); }
System.out.println(name.substring(name.indexOf(scase)+scase.length(),name.length())); }
} catch (Exception e) {
// TODO: handle exception
}finally{
HibernateUtil.closeSession(); }
}
/**
* 逻辑运算
*/
public void testCriterion5(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List grades=session.createCriteria(Grade.class).add(Restrictions.and(Restrictions.eq("gradename", "一年级"), Restrictions.le("gradeid", 5))).list();
for(int i=0;i<grades.size();i++){
System.out.println(grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
System.out.println("-------or-----------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List grades=session.createCriteria(Grade.class).add(Restrictions.or(Restrictions.eq("gradename", "一年级"), Restrictions.le("gradeid", 3))).list();
for(int i=0;i<grades.size();i++){
System.out.println(grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
System.out.println("-------not-----------");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List grades=session.createCriteria(Grade.class).add(Restrictions.not(Restrictions.eq("gradename", "一年级"))).list();
for(int i=0;i<grades.size();i++){
System.out.println(grades.get(i)); }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); } }
/**
* 集合运算
*/
public void testCriterion6(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List grades=session.createCriteria(Grade.class).add(Restrictions.isNotEmpty("stu")).list();
for(int i=0;i<grades.size();i++){
System.out.println(((Grade)grades.get(i)).getStu());
} } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
} /**
* 动态查询
*/
public void testTrends(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
TrStudent tr=new TrStudent();
tr.setName("%eli%");
tr.setStartGrade(1);
tr.setEndGrade(3);
Criteria cri= session.createCriteria(Student.class);
if(tr.getName()!=null){
cri.add(Restrictions.like("name", tr.getName()));
}if(tr.getStartGrade()!=null&&tr.getEndGrade()!=null){
cri.add(Restrictions.between("gradeid",tr.getStartGrade(),tr.getEndGrade())); }if(tr.getStartGrade()!=null&&tr.getEndGrade()==null){
cri.add(Restrictions.ge("gradeid",tr.getStartGrade())); }
if(tr.getStartGrade()==null&&tr.getEndGrade()!=null){
cri.add(Restrictions.le("gradeid",tr.getEndGrade())); }
List student=cri.addOrder(Order.asc("gradeid")).setMaxResults(80).list();
//根据年级排序,每页显示十条
Integer pagesize=10;
Integer page=1;
System.out.println(student.size()/pagesize);
for(int i=0;i<student.size()/pagesize;i++){
System.out.println("--------第 "+page+" 页-------------");
List students=cri.addOrder(Order.asc("gradeid")).setFirstResult(pagesize*(page-1)).setMaxResults(pagesize).list();
page++;
for(int j=0;j<students.size();j++){
System.out.println(students.get(j));
}
System.out.println(page); } } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
} }
/**
* 链接查询
*/
public void testrelevance(){
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List student=session.createCriteria(Student.class).createCriteria("grade").addOrder(Order.asc("gradeid")).setMaxResults(20).list();
for(int i=0;i<student.size();i++){
System.out.println(student.get(i)+"\t"+((Student)student.get(i)).getGrade().getGradename());
} } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
System.out.println("---createAlias()查询---");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
List student=session.createCriteria(Student.class,"s").createAlias("grade","g").addOrder(Order.asc("s.gradeid")).setMaxResults(20).list();
for(int i=0;i<student.size();i++){
System.out.println(student.get(i)+"\t"+((Student)student.get(i)).getGrade().getGradename());
} } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
} /**
* 投影查询
*/
public void testProj(){
System.out.println("--查询记录总数--");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//查询所有年级名称
Object obj=session.createCriteria(Grade.class)
.setProjection(Projections.projectionList().add(Projections.rowCount()))
.list();
System.out.println("所有班级:"+obj); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
} System.out.println("--查询班级名称--");
try {
session=HibernateUtil.currentSession();
session.beginTransaction();
//查询所有年级名称
Object obj=session.createCriteria(Grade.class)
.setProjection(Projections.projectionList().add(Property.forName("gradename")))
.list();
System.out.println(obj); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
} /**
* DetachedCriteria 离线查询
*/
public void testoff_line(){
try {
//这段代码一般放在web产生查询条件
DetachedCriteria det=DetachedCriteria.forClass(Student.class,"s")
.createAlias("s.grade", "g")
.add(Restrictions.eq("g.gradename", "幼儿园")); //数据访问层
session=HibernateUtil.currentSession();
session.beginTransaction();
List students=det.getExecutableCriteria(session).add(Restrictions.ilike("s.name","%yap%")).setMaxResults(50).list();
//打印
for(int i=0;i<students.size();i++){
System.out.println(students.get(i)+"\t"+((Student)students.get(i)).getGrade().getGradename());
} } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
HibernateUtil.closeSession(); }
}
/**注解 的效果
* 启动时会在数据库创建一个表
*/
public void testNote(){
try {
AnnotationConfiguration anc=new AnnotationConfiguration().configure();
session=anc.buildSessionFactory().openSession();
session.beginTransaction();
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}finally{
session.close();
} } }

Criterion&DetachedCriteria

Criterion & DetachedCriteria的更多相关文章

  1. 利用DetachedCriteria构建HQL参数动态匹配

    此文章是基于 搭建SpringMVC+Spring+Hibernate平台 1. DetachedCriteria构建类:CriteriaBuilder.java package com.ims.pe ...

  2. 基于 SSH 框架的 Criteria 和 DetachedCriteria 多条件查询

    Hibernate 定义了 CriteriaSpecification 接口规范用来完成面向对象的条件查询,Criteria 和 DetachedCriteria 就是 CriteriaSpecifi ...

  3. Hibernate框架之Criteria查询 和注解(重点☆☆☆☆☆,难点☆☆☆)

    写好一篇博客,不是容易的事.原因是:你要给自己以后看的时候,还能看懂,最重要的是当别人看到你的博客文章的时候,也一样很清楚的明白你自己写的东西.其实这也是一种成就感!! 对于每一个知识点,要有必要的解 ...

  4. 搭建SpringMVC+Spring+Hibernate平台

    一. 开发环境 1. 点击此查看并下载需要的 Eclipse IDE for Java EE Developers 开发工具,推荐选用32位   2. 点击此查看并下载需要的 MySQL Server ...

  5. 【Java 新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件

    首先给出基本Dao层代码: GenericDao.java package com.agen.dao; import java.io.Serializable; import java.util.Co ...

  6. hibernate基础dao类

    此文章是基于 搭建SpringMVC+Spring+Hibernate平台 功能:数据库的保存.更新.删除:sql.hql查询:分页查询:调用存储过程 创建hibernate基础dao类: BaseD ...

  7. hibernate-criteria查询(二)

     Restrictions 类的作用是什么? Criteria 接口没有 iterate() 方法. Criteria 查询如何对查询结果排序.分页? Criteria 查询如何实现关联? ...

  8. 6Hibernate进阶----青软S2SH(笔记)

    关于关联关系的配置,用注解配置如下(这里引用的jar包是javax.persistence) // @ManyToOne(fetch=FetchType.LAZY) @ManyToOne(fetch= ...

  9. hibernate----(Hql)另一种查询---利用Criteria类

    package com.etc.test; import java.util.List; import org.hibernate.Criteria;import org.hibernate.Sess ...

随机推荐

  1. js树形控件

    js树形控件 ztree http://www.treejs.cn/

  2. java工具类目录

    1 读取properties文件数据 http://www.cnblogs.com/xumin/p/3143762.html 2 发送邮件 3 发送短信 4

  3. mybatis父子表批量插入

    <!--父子表批量插入 --> <insert id="insertBatch" parameterType="com.niwopay.dto.beni ...

  4. css样式管理

    css命名 传统网站页面(企业级),大概就是about,product,register等,他们的名字较好区分,他们的样式整体也不会很大,用简单的驼峰法就够了,或者简单的模块. 非传统企业页面,命名驼 ...

  5. python file模块 替换输入内容脚本

    root@python-10:/home/liujianzuo/python/test# ls passwd rc.local test1 root@python-10:/home/liujianzu ...

  6. Java 集合的基本用法

    package jaxpsax; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; i ...

  7. PowerShell 常用命令

    下载文件 http://powershell.com/cs/blogs/tips/archive/2012/10/11/downloading-files-from-internet.aspx Pow ...

  8. c++11 auto unique_ptr 等

    c++11 条款21:尽量使用std::make_unique和std::make_shared而不直接使用new c++11 条款18: 使用std::unique_ptr来进行独享所有权的资源管理 ...

  9. 欧几里得算法:从证明等式gcd(m, n) = gcd(n, m mod n)对每一对正整数m, n都成立说开去

    写诗或者写程序的时候,我们经常要跟欧几里得算法打交道.然而有没要考虑到为什么欧几里得算法是有效且高效的,一些偏激(好吧,请允许我用这个带有浓重个人情感色彩的词汇)的计算机科学家认为,除非程序的正确性在 ...

  10. IOS密码加密

    一般使用两种加密技术 1.MD5 2.以前是SHA1加密  现在流行是SHA-2加密