返回介绍

集合的检索

发布于 2025-04-21 21:42:12 字数 4218 浏览 0 评论 0 收藏 0

你可能会认为从数据库中把集合信息检索出来同样也是这么简单。没错!这一节将改进一下我们的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。