JDBC一对多连接与多个选择

时间:2016-10-02 14:08:28

标签: java mysql jdbc

我目前正在编写一个程序,我需要从数据库中选择一个具有多个一对多关系的实体。在这个程序中,路由由许多路由点组成的主要对象有许多注释和许多报告。这意味着如果我想从数据库中选择一条路线及其路线点,评论和报告作为连接的结果,我将获得多行,其中包含重复信息。

据我所知,这意味着如果我已经“看到”这个RoutePoint,报告或评论,我将不得不循环每一行并保留一组。由于路线可以有大量的路线点,我想这会很慢,而且非常复杂和杂乱。我在下面列出了这个样子。

HashSet<String> commentIds = new HashSet<String>();
HashSet<String> routePointIds = new HashSet<String>();
HashSet<String> reportIds = new HashSet<String>();

Route route = null;
        while (resultSet.next()) {
            String commentId = resultSet.getString("commentId");
            String routePointId = resultSet.getString("routePointId");
            String reportId = resultSet.getString("reportId");

            if(route == null){
                // create route from result set
            }

            if(!commentIds.contains(commentId)){
                // create comment object from result set
                // add to route object

                commentIds.add(commentId);
            }

            if(!routePointIds.contains(routePointId)){
                // create route point object from result set
                // add to route object

                routePointIds.add(routePointId);
            }

            if(!reportIds.contains(reportId)){
                // create comment object from result set
                // add to route

                reportIds.add(reportId);
            }

        }

我的问题是,是否有一种更简单的方法来处理JDBC中多个一对多连接的查询?

我想到的另一种方法是做多个选择。每个表一个而不是加入。我不确定这是否是一种合适的方法,因为它意味着多次查询数据库,而不仅仅是一次。

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

查询每个独立结果集的不同行。由于您只查询一个路由的数据,我假设您没有将其存储在缓存或内存中,并且需要在需要路由数据时执行此操作。使用优化查询会更高效,并且避免返回每行的java逻辑来清除重复数据。

相关问题