【问题标题】:iterate result set to create object as required迭代结果集以根据需要创建对象
【发布时间】:2013-04-17 09:15:22
【问题描述】:

大家好。我有以下结果集,现在我希望将其保存在 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

【问题讨论】:

  • 您的问题是什么?您遇到了什么问题,您尝试过什么?
  • 这是一个错误的数据库设计!!!

标签: java javabeans resultset


【解决方案1】:

使用地图来存储您的主题:

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-10-25
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2010-10-11
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多