大家好。我有以下结果集,现在我希望它保存在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
答案 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();