Here is one solution.
这是一个解决方案
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "- "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Calendar">
<resultMap id="quarterMap" class="calendarQuarter" groupBy="quarter">
<result property="quarter" column="quarter"/>
<result property="name" column="name"/>
<result property="description" column="description"/>
<result property="months" resultMap="Calendar.monthMap"/>
</resultMap>
<resultMap id="monthMap" class="calendarMonth">
<result property="name" column="monthName"/>
<result property="description" column="monthDescription"/>
<result property="broadcastStartDate" column="broadcastStartDate"/>
<result property="broadcastEndDate" column="broadcastEndDate"/>
</resultMap>
<select id="getQuartersForServiceYear" resultMap="quarterMap">
select distinct
QuarterNumber as quarter,
QuarterName as name,
QuarterDesc as description,
SeasonYear as year,
MonthName as monthName,
MonthDesc as monthDescription,
min(broadcastDate) as broadcastStartDate,
max(broadcastDate) as broadcastEndDate
from BroadcastDate
where SeasonYear = #year#
and MonthName is not null
group by
QuarterDesc,
QuarterNumber,
QuarterName,
SeasonYear,
MonthName,
MonthDesc
order by broadcastStartDate
</select>
</sqlMap>
When you call
接着你可以调用
List myList = executeQueryForList("Calendar.getQuartersForServiceYear", 2005);
the main query is executed, and the results are stored in the
myList variable as beans of type "calendarQuarter" (an alias). Each object in that List will have a "months" property that is also a List populated from the same query, but using the "monthMap" result map to populate the beans in the child lists. So, you end up with a list containing sub-lists, and only one database query is executed.
主查询被执行,并且在myList里存储calendarQuarter为别名的对象。在List里的每个“months”属性里还有一个初始化的子列表,这个子列表的数据也来自这次查询。但是用monthMap结果map来渲染子列表。所以,你得到了一个含有子列表的列表,并且只有一次数据库查询被执行。
The important items here are the
重要的项在groupby的属性和months属性。
attribute and the
<result property="months" resultMap="Calendar.monthMap"/>
property mapping in the "quarterMap" result map. One other important detail is that the result mapping for the months property is namespace aware - had it been simply "monthMap" it would not work.
另一个需要注意的是month属性的结果映射名是命名空间敏感的-如果配置成“monthMap”,他将不能工作。
Summary: You have a single query that will return results such as
总结:你有一个简单的查询,他返回下面这样的结果
parent1, child1
parent1, child2
parent2, child1
parent3, child1
parent3, child2
parent3, child3
....
The groupby will take care of figuring out that you really want a list of parent objects with their matching child objects as a list under them.
这个groupby将处理你想得到的父对象组成的列表和相应的在父对象之下的子对象组成的列表。