-2

在此处输入图像描述

大家好。我有以下结果集,现在我希望将其保存在 java bean 中。我有两个 java beans(pojo)。

public class Topic{
private int topic_id;
private String topic;
private List<SubTopic> subTopicList;

//getter setter
}

public class SubTopic{
    private int sub_topic_id;
private String sub_topic;
//getter and setter
}

现在我想设置我的Topic对象,使其包含一个主题和所有子主题的列表。但是我在迭代结果集时遇到问题。为了更清楚地说明一个包含心脏病学的主题对象应该有,

topic_id=73
topic=Cardiology
List<SubTopic> subTopic=//this includes id and name of SubTopic and SubTopic2

同样的另一个对象应该是过敏、哮喘、免疫学。

ResultSet rs = pstmt.executeQuery();
//now how to iterate rs to create list of topic object in required way
4

1 回答 1

2

使用地图存储您的主题:

Map<Long, Topic> topicsById = new HashMap<>();
while (rs.next()) {
    Long topicId = rs.getLong(1);
    String topicName = rs.getString(2);
    Long subTopicId = rs.getLong(3);
    String subTopicName = rs.getString(4);

    Topic topic = topicsById.get(topicId);
    if (topic == null) {
        topic = new Topic(topicId, topicName);
        topicsById.put(topicId, topic);
    }
    topic.addSubTopic(new SubTopic(subTopicId, subTopicName);
}
Collection<Topic> allTopics = topicsById.values();
于 2013-04-17T09:20:19.460 回答