迭代结果集以根据需要创建对象

时间:2013-04-17 09:15:23

标签: java javabeans resultset

enter image description here

大家好。我有以下结果集,现在我希望它保存在java bean中。我有两个java bean(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

1 个答案:

答案 0 :(得分: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();