- 译者序
- 前言
- 本书怎么使用
- 本书排版字体约定
- 本书网站
- 致谢
- 第一部分 Hibernate 快速入门
- 第 1 章 安装和设置
- 第 2 章 映射简介
- 第 3 章 驾驭 Hibernate
- 第 4 章 集合与关联
- 第 5 章 更复杂的关联
- 第 6 章 自定义值类型
- 第 7 章 映射标注
- 第 8 章 条件查询
- 第 9 章 浅谈 HQL
- 第二部分 与其他工具的集成
- 第 10 章 将 Hibernate 连接到 MySQL
- 第 11 章 Hibernate 与 Eclipse:Hibernate Tools 使用实战
- 第 12 章 Maven 进阶
- 第 13 章 Spring 入门:Hibernate 与 Spring
- 第 14 章 画龙点睛:用 Stripes 集成 Spring 和 Hibernate
- 附录 A Hibernate 类型
- 附录 B Criteria API
- 附录 C Hibernate SQL 方言
- 附录 D Spring 事务支持
- 附录 E 参考资源
- 作者简介
- 封面介绍
集合的检索
你可能会认为从数据库中把集合信息检索出来同样也是这么简单。没错!这一节将改进一下我们的 QueryTest 类,把艺人及相关的曲目显示出来。例 4-10 以粗体字展示了适当的修改和增加的代码。而且只需要新增少量的代码。
例 4-10:改进的 QueryTest.java(以便显示关联了曲目的艺人对象)
package com.oreilly.hh;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import com.oreilly.hh.data.*;
import java.sql.Time;
import java.util.*;
/**
*Retrieve data as objects
*/
public class QueryTest{
/**
*Retrieve any tracks that fit in the specified amount of time.
*
*@param length the maximum playing time for tracks to be returned.
*@param session the Hibernate session that can retrieve data.
*@return a list of{@link Track}s meeting the length restriction.
*/
public static List tracksNoLongerThan(Time length, Session session){
Query query=session.getNamedQuery(
"com.oreilly.hh.tracksNoLongerThan");
query.setTime("length",length);
return query.list();
}
/**
*Build a parenthetical, comma-separated list of artist names.
*@param artists the artists whose names are to be displayed.
*@return the formatted list, or an empty string if the set was empty.
*/
public static String listArtistNames(Set<Artist>artists){❶
StringBuilder result=new StringBuilder();
for(Artist artist:artists){
result.append((result.length()==0)?"(":",");
result.append(artist.getName());
}
if(result.length()>0){
result.append(")");
}
return result.toString();
}
/**
*Look up and print some tracks when invoked from the command line.
*/
public static void main(String args[])throws Exception{
//Create a configuration based on the XML file we've put
//in the standard place.
Configuration config=new Configuration();
config.configure();
//Get the session factory we can use for persistence
SessionFactory sessionFactory=config.buildSessionFactory();
//Ask for a session using the JDBC information we've configured
Session session=sessionFactory.openSession();
try{
//Print the tracks that will fit in seven minutes
List tracks=tracksNoLongerThan(Time.valueOf("00:07:00"),❷
session);
for(ListIterator iter=tracks.listIterator();
iter.hasNext();){
Track aTrack=(Track)iter.next();
System.out.println("Track:\""+aTrack.getTitle()+"\""+
listArtistNames(aTrack.getArtists())+❸
aTrack.getPlayTime());
}
}finally{
//No matter what, close the session
session.close();
}
//Clean up after ourselves
sessionFactory.close();
}
}
❶我们增加的第一个方法是一个小工具方法,用于漂亮地格式化一组艺人的名字,将艺人名字放在一对圆括号内,并用逗号“,”作为分隔符,再加上适当的空格。或者如果艺人集合为空的话,就什么也不显示。
❷对于新加的所有有趣的多艺人相关的曲目,其播放时间都超过 5 分钟,所以我们将查询限值增加到 7 分钟,这样才能看到结果。
❸最后,我们在 println()语句的适当位置上调用 listArtistNames()方法,描述找到的曲目信息。现在先去掉 Hibernate 的查询调试输出配置,因为这些调试信息会妨碍我们观察真正想要看到的信息。编辑 src 目录下的 hibernate.cfg.xml 文件,将 show_sql 属性修改为 false。
……
<!--Echo all executed SQL to stdout-->
<property name="show_sql">false</property>
……
这样设置以后,例 4-11 演示了执行 ant qtest 命令后,新的输出结果。
例 4-11:QueryTest 输出的艺人信息
%ant qtest
Buildfile:build.xml
prepare:
compile:
[javac]Compiling 1 source file to/Users/jim/svn/oreilly/hib_dev_2e
/current/scratch/ch04/classes
qtest:
[java]Track:"Russian Trance"(PPK)00:03:30
[java]Track:"Video Killed the Radio Star"(The Buggles)00:03:49
[java]Track:"Gravity's Angel"(Laurie Anderson)00:06:06
[java]Track:"Adagio for Strings(Ferry Corsten Remix)"(Ferry Corsten,
William Orbit, Samuel Barber)00:06:35
[java]Track:"Test Tone 1"00:00:10
BUILD SUCCESSFUL
Total time:2 seconds
你会注意到两件事。首先,可以看到这种结果显示方式比图 4-2 中简单的数字列表更容易解读。其次,运行无误!即使不带任何艺人映射数据、纯测试用的“特殊”曲目都没有问题,因为 Hibernate 采用的方法比较友好,在这种特殊情况下会创建一个不含艺人对象的空 Set 对象。免去了我们为防止引发 NullPointerException(空指针错误)异常,而自己编写代码检测对象是否为 null 的需要。
注意:但是,等一下,还有呢!不需要编写额外的代码……
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论