1、分页
使用Criteria进行分页查询
无论你使用的是Oracle,Mysql,NoSQL还是DB2,分页查询的代码写法都是一样的
2、分页,从第3个开始,一共查询5个Product
Hibernate使用Criteria 来进行分页查询
c.setFirstResult(2); 表示从第3条数据开始
c.setMaxResults(5); 表示一共查询5条数据
package com.how2java.test;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import com.how2java.pojo.Product;
public class TestHibernate {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String name = "iphone";
Criteria c= s.createCriteria(Product.class);
c.add(Restrictions.like("name", "%"+name+"%"));
c.setFirstResult(2);
c.setMaxResults(5);
List<Product> ps = c.list();
for (Product p : ps) {
System.out.println(p.getName());
}
s.getTransaction().commit();
s.close();
sf.close();
}
}
3、延迟加载
load方式是延迟加载,只有属性被访问的时候才会调用sql语句
get方式是非延迟加载,无论后面的代码是否会访问到属性,马上执行sql语句
package com.how2java.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.how2java.pojo.Product;
public class TestHibernate {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
System.out.println("log1");
Product p = (Product) s.get(Product.class, 1);
System.out.println("log2");
Product p2 = (Product) s.load(Product.class, 2);
System.out.println("log3");
System.out.println(p2.getName());
System.out.println("log4");
s.getTransaction().commit();
s.close();
sf.close();
}
}
4、对于id不存在的对象的处理
都通过id=500去获取对象
- get方式会返回null
- load方式会抛出异常
package com.how2java.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.how2java.pojo.Product;
public class TestHibernate {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
System.out.println("log1");
Product p = (Product)s.get(Product.class, 5);
System.out.println("log2");
Product p2 = (Product)s.load(Product.class, 5);
System.out.println("log3");
Product p3 = (Product)s.get(Product.class, 500);
System.out.println("p3="+p3);
Product p4 = (Product)s.load(Product.class, 500);
System.out.println("p3="+p4);
s.getTransaction().commit();
s.close();
sf.close();
}
}