Hibernate目前总共分为三大类查询:cretiria,hql,本地sql 【以下篇章搜集于网络,感谢作者】
第一:关于cretiria的查询
具有一个直观的、可扩展的条件查询API是Hibernate的特色。
15.1. 创建一个Criteria 实例
org.hibernate.Criteria接口表示特定持久类的一个查询。Session是 Criteria实例的工厂。
- <SPAN style="FONT-SIZE: medium">Criteria crit = sess.createCriteria(Cat.class);
- crit.setMaxResults(50);
- List cats = crit.list();</SPAN>
- <span style="font-size: medium;">Criteria crit = sess.createCriteria(Cat.class);
- crit.setMaxResults(50);
- List cats = crit.list();</span>
15.2. 限制结果集内容
一个单独的查询条件是org.hibernate.criterion.Criterion 接口的一个实例。org.hibernate.criterion.Restrictions类 定义了获得某些内置Criterion类型的工厂方法。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .add( Restrictions.between("weight", minWeight, maxWeight) )
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .add( Restrictions.between("weight", minWeight, maxWeight) )
- .list();
- </span>
约束可以按逻辑分组。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .add( Restrictions.or(
- Restrictions.eq( "age", new Integer(0) ),
- Restrictions.isNull("age")
- ) )
- .list();
- List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
- .add( Restrictions.disjunction()
- .add( Restrictions.isNull("age") )
- .add( Restrictions.eq("age", new Integer(0) ) )
- .add( Restrictions.eq("age", new Integer(1) ) )
- .add( Restrictions.eq("age", new Integer(2) ) )
- ) )
- .list();</SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .add( Restrictions.or(
- Restrictions.eq( "age", new Integer(0) ),
- Restrictions.isNull("age")
- ) )
- .list();
- List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
- .add( Restrictions.disjunction()
- .add( Restrictions.isNull("age") )
- .add( Restrictions.eq("age", new Integer(0) ) )
- .add( Restrictions.eq("age", new Integer(1) ) )
- .add( Restrictions.eq("age", new Integer(2) ) )
- ) )
- .list();</span>
Hibernate提供了相当多的内置criterion类型(Restrictions 子类), 但是尤其有用的是可以允许你直接使用SQL。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.sql("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) )
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.sql("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) )
- .list();
- </span>
{alias}占位符应当被替换为被查询实体的列别名。
Property实例是获得一个条件的另外一种途径。你可以通过调用Property.forName() 创建一个Property。
- <SPAN style="FONT-SIZE: medium">Property age = Property.forName("age");
- List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.disjunction()
- .add( age.isNull() )
- .add( age.eq( new Integer(0) ) )
- .add( age.eq( new Integer(1) ) )
- .add( age.eq( new Integer(2) ) )
- ) )
- .add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) )
- .list();</SPAN>
- <span style="font-size: medium;">Property age = Property.forName("age");
- List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.disjunction()
- .add( age.isNull() )
- .add( age.eq( new Integer(0) ) )
- .add( age.eq( new Integer(1) ) )
- .add( age.eq( new Integer(2) ) )
- ) )
- .add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) )
- .list();</span>
15.3. 结果集排序
你可以使用org.hibernate.criterion.Order来为查询结果排序。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "F%")
- .addOrder( Order.asc("name") )
- .addOrder( Order.desc("age") )
- .setMaxResults(50)
- .list();
- List cats = sess.createCriteria(Cat.class)
- .add( Property.forName("name").like("F%") )
- .addOrder( Property.forName("name").asc() )
- .addOrder( Property.forName("age").desc() )
- .setMaxResults(50)
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "F%")
- .addOrder( Order.asc("name") )
- .addOrder( Order.desc("age") )
- .setMaxResults(50)
- .list();
- List cats = sess.createCriteria(Cat.class)
- .add( Property.forName("name").like("F%") )
- .addOrder( Property.forName("name").asc() )
- .addOrder( Property.forName("age").desc() )
- .setMaxResults(50)
- .list();
- </span>
15.4. 关联
你可以使用createCriteria()非常容易的在互相关联的实体间建立 约束。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "F%")
- .createCriteria("kittens")
- .add( Restrictions.like("name", "F%")
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "F%")
- .createCriteria("kittens")
- .add( Restrictions.like("name", "F%")
- .list();
- </span>
注意第二个 createCriteria()返回一个新的 Criteria实例,该实例引用kittens 集合中的元素。
接下来,替换形态在某些情况下也是很有用的。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .createAlias("kittens", "kt")
- .createAlias("mate", "mt")
- .add( Restrictions.eqProperty("kt.name", "mt.name") )
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .createAlias("kittens", "kt")
- .createAlias("mate", "mt")
- .add( Restrictions.eqProperty("kt.name", "mt.name") )
- .list();
- </span>
(createAlias()并不创建一个新的 Criteria实例。)
Cat实例所保存的之前两次查询所返回的kittens集合是 没有被条件预过滤的。如果你希望只获得符合条件的kittens, 你必须使用returnMaps()。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .createCriteria("kittens", "kt")
- .add( Restrictions.eq("name", "F%") )
- .returnMaps()
- .list();
- Iterator iter = cats.iterator();
- while ( iter.hasNext() ) {
- Map map = (Map) iter.next();
- Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
- Cat kitten = (Cat) map.get("kt");
- }
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .createCriteria("kittens", "kt")
- .add( Restrictions.eq("name", "F%") )
- .returnMaps()
- .list();
- Iterator iter = cats.iterator();
- while ( iter.hasNext() ) {
- Map map = (Map) iter.next();
- Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
- Cat kitten = (Cat) map.get("kt");
- }
- </span>
15.5. 动态关联抓取
你可以使用setFetchMode()在运行时定义动态关联抓取的语义。
- <SPAN style="FONT-SIZE: medium">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .setFetchMode("mate", FetchMode.EAGER)
- .setFetchMode("kittens", FetchMode.EAGER)
- .list();
- </SPAN>
- <span style="font-size: medium;">List cats = sess.createCriteria(Cat.class)
- .add( Restrictions.like("name", "Fritz%") )
- .setFetchMode("mate", FetchMode.EAGER)
- .setFetchMode("kittens", FetchMode.EAGER)
- .list();
- </span>
这个查询可以通过外连接抓取mate和kittens。 查看第 19.1 节 “ 抓取策略(Fetching strategies) ”可以获得更多信息。
15.6. 查询示例
org.hibernate.criterion.Example类允许你通过一个给定实例 构建一个条件查询。
- <SPAN style="FONT-SIZE: medium">Cat cat = new Cat();
- cat.setSex('F');
- cat.setColor(Color.BLACK);
- List results = session.createCriteria(Cat.class)
- .add( Example.create(cat) )
- .list();</SPAN>
- <span style="font-size: medium;">Cat cat = new Cat();
- cat.setSex('F');
- cat.setColor(Color.BLACK);
- List results = session.createCriteria(Cat.class)
- .add( Example.create(cat) )
- .list();</span>
版本属性、标识符和关联被忽略。默认情况下值为null的属性将被排除。
你可以自行调整Example使之更实用。
- <SPAN style="FONT-SIZE: medium">Example example = Example.create(cat)
- .excludeZeroes() //exclude zero valued properties
- .excludeProperty("color") //exclude the property named "color"
- .ignoreCase() //perform case insensitive string comparisons
- .enableLike(); //use like for string comparisons
- List results = session.createCriteria(Cat.class)
- .add(example)
- .list();</SPAN>
- <span style="font-size: medium;">Example example = Example.create(cat)
- .excludeZeroes() //exclude zero valued properties
- .excludeProperty("color") //exclude the property named "color"
- .ignoreCase() //perform case insensitive string comparisons
- .enableLike(); //use like for string comparisons
- List results = session.createCriteria(Cat.class)
- .add(example)
- .list();</span>
你甚至可以使用examples在关联对象上放置条件。
- <SPAN style="FONT-SIZE: medium">List results = session.createCriteria(Cat.class)
- .add( Example.create(cat) )
- .createCriteria("mate")
- .add( Example.create( cat.getMate() ) )
- .list();
- </SPAN>
- <span style="font-size: medium;">List results = session.createCriteria(Cat.class)
- .add( Example.create(cat) )
- .createCriteria("mate")
- .add( Example.create( cat.getMate() ) )
- .list();
- </span>
15.7. 投影(Projections)、聚合(aggregation)和分组(grouping)
org.hibernate.criterion.Projections是 Projection 的实例工厂。我们通过调用 setProjection()应用投影到一个查询。
在一个条件查询中没有必要显式的使用 "group by" 。某些投影类型就是被定义为 分组投影,他们也出现在SQL的group by子句中。
你可以选择把一个别名指派给一个投影,这样可以使投影值被约束或排序所引用。下面是两种不同的实现方式:
- <SPAN style="FONT-SIZE: medium">List results = session.createCriteria(Cat.class)
- .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) )
- .addOrder( Order.asc("colr") )
- .list();
- List results = session.createCriteria(Cat.class)
- .setProjection( Projections.groupProperty("color").as("colr") )
- .addOrder( Order.asc("colr") )
- .list();
- </SPAN>
- <span style="font-size: medium;">List results = session.createCriteria(Cat.class)
- .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) )
- .addOrder( Order.asc("colr") )
- .list();
- List results = session.createCriteria(Cat.class)
- .setProjection( Projections.groupProperty("color").as("colr") )
- .addOrder( Order.asc("colr") )
- .list();
- </span>
alias()和as()方法简便的将一个投影实例包装到另外一个 别名的Projection实例中。简而言之,当你添加一个投影到一个投影列表中时 你可以为它指定一个别名:
- <SPAN style="FONT-SIZE: medium">List results = session.createCriteria(Cat.class)
- .setProjection( Projections.projectionList()
- .add( Projections.rowCount(), "catCountByColor" )
- .add( Projections.avg("weight"), "avgWeight" )
- .add( Projections.max("weight"), "maxWeight" )
- .add( Projections.groupProperty("color"), "color" )
- )
- .addOrder( Order.desc("catCountByColor") )
- .addOrder( Order.desc("avgWeight") )
- .list();
- List results = session.createCriteria(Domestic.class, "cat")
- .createAlias("kittens", "kit")
- .setProjection( Projections.projectionList()
- .add( Projections.property("cat.name"), "catName" )
- .add( Projections.property("kit.name"), "kitName" )
- )
- .addOrder( Order.asc("catName") )
- .addOrder( Order.asc("kitName") )
- .list();</SPAN>
- <span style="font-size: medium;">List results = session.createCriteria(Cat.class)
- .setProjection( Projections.projectionList()
- .add( Projections.rowCount(), "catCountByColor" )
- .add( Projections.avg("weight"), "avgWeight" )
- .add( Projections.max("weight"), "maxWeight" )
- .add( Projections.groupProperty("color"), "color" )
- )
- .addOrder( Order.desc("catCountByColor") )
- .addOrder( Order.desc("avgWeight") )
- .list();
- List results = session.createCriteria(Domestic.class, "cat")
- .createAlias("kittens", "kit")
- .setProjection( Projections.projectionList()
- .add( Projections.property("cat.name"), "catName" )
- .add( Projections.property("kit.name"), "kitName" )
- )
- .addOrder( Order.asc("catName") )
- .addOrder( Order.asc("kitName") )
- .list();</span>
你也可以使用Property.forName()来表示投影:
- <SPAN style="FONT-SIZE: medium">List results = session.createCriteria(Cat.class)
- .setProjection( Property.forName("name") )
- .add( Property.forName("color").eq(Color.BLACK) )
- .list();
- List results = session.createCriteria(Cat.class)
- .setProjection( Projections.projectionList()
- .add( Projections.rowCount().as("catCountByColor") )
- .add( Property.forName("weight").avg().as("avgWeight") )
- .add( Property.forName("weight").max().as("maxWeight") )
- .add( Property.forName("color").group().as("color" )
- )
- .addOrder( Order.desc("catCountByColor") )
- .addOrder( Order.desc("avgWeight") )
- .list();</SPAN>
- <span style="font-size: medium;">List results = session.createCriteria(Cat.class)
- .setProjection( Property.forName("name") )
- .add( Property.forName("color").eq(Color.BLACK) )
- .list();
- List results = session.createCriteria(Cat.class)
- .setProjection( Projections.projectionList()
- .add( Projections.rowCount().as("catCountByColor") )
- .add( Property.forName("weight").avg().as("avgWeight") )
- .add( Property.forName("weight").max().as("maxWeight") )
- .add( Property.forName("color").group().as("color" )
- )
- .addOrder( Order.desc("catCountByColor") )
- .addOrder( Order.desc("avgWeight") )
- .list();</span>
15.8. 离线(detached)查询和子查询
DetachedCriteria类使你在一个session范围之外创建一个查询,并且可以使用任意的 Session来执行它。
- <SPAN style="FONT-SIZE: medium">DetachedCriteria query = DetachedCriteria.forClass(Cat.class)
- .add( Property.forName("sex").eq('F') );
- Session session = ....;
- Transaction txn = session.beginTransaction();
- List results = query.getExecutableCriteria(session).setMaxResults(100).list();
- txn.commit();
- session.close();
- DetachedCriteria也可以用以表示子查询。条件实例包含子查询可以通过 Subqueries或者Property获得。
- DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
- .setProjection( Property.forName("weight").avg() );
- session.createCriteria(Cat.class)
- .add( Property.forName("weight).gt(avgWeight) )
- .list();
- DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
- .setProjection( Property.forName("weight") );
- session.createCriteria(Cat.class)
- .add( Subqueries.geAll("weight", weights) )
- .list();</SPAN>
- <span style="font-size: medium;">DetachedCriteria query = DetachedCriteria.forClass(Cat.class)
- .add( Property.forName("sex").eq('F') );
- Session session = ....;
- Transaction txn = session.beginTransaction();
- List results = query.getExecutableCriteria(session).setMaxResults(100).list();
- txn.commit();
- session.close();
- DetachedCriteria也可以用以表示子查询。条件实例包含子查询可以通过 Subqueries或者Property获得。
- DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
- .setProjection( Property.forName("weight").avg() );
- session.createCriteria(Cat.class)
- .add( Property.forName("weight).gt(avgWeight) )
- .list();
- DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
- .setProjection( Property.forName("weight") );
- session.createCriteria(Cat.class)
- .add( Subqueries.geAll("weight", weights) )
- .list();</span>
甚至相互关联的子查询也是有可能的:
- <SPAN style="FONT-SIZE: medium">DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Cat.class, "cat2")
- .setProjection( Property.forName("weight").avg() )
- .add( Property.forName("cat2.sex").eqProperty("cat.sex") );
- session.createCriteria(Cat.class, "cat")
- .add( Property.forName("weight).gt(avgWeightForSex) )
- .list();</SPAN>
- <span style="font-size: medium;">DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Cat.class, "cat2")
- .setProjection( Property.forName("weight").avg() )
- .add( Property.forName("cat2.sex").eqProperty("cat.sex") );
- session.createCriteria(Cat.class, "cat")
- .add( Property.forName("weight).gt(avgWeightForSex) )
- .list();</span>
第二:HQL查询
在HQL中关键字不区分大小写,但是属性和类名区分大小写,下面介绍各种类型的Hibernate的HQL查询。
1、Hibernate HQL查询:简单属性查询
* 单一属性查询,返回结果集属性列表,元素类型和实体类中相应的属性类型一致
* 多个属性查询,返回的集合元素是对象数组,数组元素的类型和对应的属性在实体类中的类型一致
数组的长度取决与select中属性的个数
* 如果认为返回数组不够对象化,可以采用HQL动态实例化Student对象
2、Hibernate HQL查询:实体对象查询
* N + 1问题,在默认情况下,使用query.iterate查询,有可以能出现N+1问题,所谓的N+1是在查询的时候发出了N+1条sql语句,1: 首先发出一条查询对象id列表的sql,N: 根据id列表到缓存中查询,如果缓存中不存在与之匹配的数据,那么会根据id发出相应的sql语句
* list和iterate的区别?
* list每次都会发出sql语句,list会向缓存中放入数据,而不利用缓存中的数据
* iterate:在默认情况下iterate利用缓存数据,但如果缓存中不存在数据有可以能出现N+1问题
3、Hibernate HQL查询:条件查询
* 可以采用拼字符串的方式传递参数
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery("select s.id, s.name from Student s where s.name like '%1%'").list(); </SPAN>
- <span style="font-size: medium;">List students = session.createQuery("select s.id, s.name from Student s where s.name like '%1%'").list(); </span>
* 可以采用 ?来传递参数(索引从0开始)
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery("select s.id, s.name from Student s where s.name like ?").setParameter(0, "%1%").list(); //可以使用?方式传递参数 //参数的索引从0开始 //传递的参数值,不用单引号引起来 //注意方法链编程 </SPAN>
- <span style="font-size: medium;">List students = session.createQuery("select s.id, s.name from Student s where s.name like ?").setParameter(0, "%1%").list(); //可以使用?方式传递参数 //参数的索引从0开始 //传递的参数值,不用单引号引起来 //注意方法链编程 </span>
* 可以采用 :参数名 来传递参数
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery ("select s.id, s.name from Student s where s.name like :myname").setParameter("myname", "%1%").list(); </SPAN>
- <span style="font-size: medium;">List students = session.createQuery ("select s.id, s.name from Student s where s.name like :myname").setParameter("myname", "%1%").list(); </span>
* 如果传递多个参数,可以采用setParamterList方法
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery("select s.id, s.name from Student s where s.id in(:myids)").setParameterList("myids", new Object[]{1, 2, 3, 4, 5}).list();</SPAN>
- <span style="font-size: medium;">List students = session.createQuery("select s.id, s.name from Student s where s.id in(:myids)").setParameterList("myids", new Object[]{1, 2, 3, 4, 5}).list();</span>
* 在HQL中可以使用数据库的函数,如:date_format
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery("select s.id, s.name from Student s where date_format(s.createTime, '%Y-%m')=?").setParameter(0, "2008-02").list(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //查询2008-01-10到2008-02-15创建的学生 List students = session.createQuery("select s.id, s.name from Student s where s.createTime between ? and ?") .setParameter(0, sdf.parse("2008-01-10 00:00:00")) .setParameter(1, sdf.parse("2008-02-15 23:59:59")) .list(); </SPAN>
- <span style="font-size: medium;">List students = session.createQuery("select s.id, s.name from Student s where date_format(s.createTime, '%Y-%m')=?").setParameter(0, "2008-02").list(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //查询2008-01-10到2008-02-15创建的学生 List students = session.createQuery("select s.id, s.name from Student s where s.createTime between ? and ?") .setParameter(0, sdf.parse("2008-01-10 00:00:00")) .setParameter(1, sdf.parse("2008-02-15 23:59:59")) .list(); </span>
4、Hibernate HQL查询:直接使用sql进行查询
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createSQLQuery("select * from t_student").list(); </SPAN>
- <span style="font-size: medium;">List students = session.createSQLQuery("select * from t_student").list(); </span>
不会返回对象,而是所有属性!
5、Hibernate HQL查询:分页查询
* setFirstResult(),从0开始
* setMaxResults,每页显示多少条数据
Java代码:
- <SPAN style="FONT-SIZE: medium">List students = session.createQuery("from Student") .setFirstResult(1) .setMaxResults(2) .list(); </SPAN>
- <span style="font-size: medium;">List students = session.createQuery("from Student") .setFirstResult(1) .setMaxResults(2) .list(); </span>
6、Hibernate HQL查询:对象导航查询,在HQL中采用 . 进行导航
7、Hibernate HQL查询:连接查询
* 内连
Sql代码:
- <SPAN style="FONT-SIZE: medium">SELECT s.name, c.name FROM Student s (inner) join s.classes c </SPAN>
- <span style="font-size: medium;">SELECT s.name, c.name FROM Student s (inner) join s.classes c </span>
* 外连接(左连接/右连接)
Sql代码:
- <SPAN style="FONT-SIZE: medium">SELECT s.name, c.name FROM Student s left join s.classes c </SPAN>
- <span style="font-size: medium;">SELECT s.name, c.name FROM Student s left join s.classes c </span>
8、Hibernate HQL查询:统计查询
Java代码:
- <SPAN style="FONT-SIZE: medium">List students =session.createQuery("select c.name, count(s) from Student s join s.classes c " +"group by c.name order by c.name").list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Object[] obj = (Object[])iter.next(); System.out.println(obj[0] + ", " + obj[1]); } </SPAN>
- <span style="font-size: medium;">List students =session.createQuery("select c.name, count(s) from Student s join s.classes c " +"group by c.name order by c.name").list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Object[] obj = (Object[])iter.next(); System.out.println(obj[0] + ", " + obj[1]); } </span>
9、DML风格的操作(尽量少用,因为和缓存不同步)
Java代码:
- <SPAN style="FONT-SIZE: medium">session.createQuery ("update Student s set s.name=? where s.id < ?") .setParameter(0, "李四") .setParameter(1, 5) .executeUpdate(); </SPAN>
- <span style="font-size: medium;">session.createQuery ("update Student s set s.name=? where s.id < ?") .setParameter(0, "李四") .setParameter(1, 5) .executeUpdate(); </span>
应当尽量少用,因为和缓存不同步,也就是说,假如在执行上面的语句之前,已经把student封装成一个list曾经拿了出来,再执行上面的语句对 student中的表进行数据更新,然后再list Student表,则此时的list是从缓存中取的数据,而不是从表中找到的数据,也就是说,list拿到的是update前的数据,所以造成了这种不同步,所以这种风格尽量少用。
从这个方面也可以看得出Hibernate并不适用于聚集性,统计,大量批量的更新,删除等操作。
第三,本地SQL查询
使用SQLQuery
对原生SQL查询执行的控制是通过SQLQuery接口进行的,通过执行Session.createSQLQuery()获取这个接口。最简单的情况下,我们可以采用以下形式:
- <SPAN style="FONT-SIZE: medium">List cats = sess.createSQLQuery( " select * from cats " ).addEntity(Cat. class ).list(); </SPAN>
- <span style="font-size: medium;">List cats = sess.createSQLQuery( " select * from cats " ).addEntity(Cat. class ).list(); </span>
这个查询指定了:
SQL查询字符串
查询返回的实体
这里,结果集字段名被假设为与映射文件中指明的字段名相同。对于连接了多个表的查询,这就可能造成问题,因为可能在多个表中出现同样名字的字段。下面的方法就可以避免字段名重复的问题:
- <SPAN style="FONT-SIZE: medium">List cats = sess.createSQLQuery( " select {cat.*} from cats cat " ).addEntity( " cat " , Cat. class ).list(); </SPAN>
- <span style="font-size: medium;">List cats = sess.createSQLQuery( " select {cat.*} from cats cat " ).addEntity( " cat " , Cat. class ).list(); </span>
这个查询指定了:
SQL查询语句,它带一个占位符,可以让Hibernate使用字段的别名.
查询返回的实体,和它的SQL表的别名.
addEntity()方法将SQL