我目前正在编写一个程序,我需要从数据库中选择一个具有多个一对多关系的实体。在此程序中,路线的主要对象由许多路线点组成,具有许多注释和许多报告。这意味着,如果我想从数据库中选择一条路线及其路线点、评论和报告作为连接的结果,我将返回多行,其中包含重复信息。
据我所知,这意味着我必须在每一行上循环并保留一组(如果我已经“看到”了此 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 中具有多个一对多联接的查询?
我想到的另一种解决方法是进行多重选择。每张 table 一个,而不是加入。我不确定这是否是一种合适的方法,因为这意味着多次查询数据库而不仅仅是一次。
感谢您的回复。
最佳答案
查询每个独立结果集的不同行。由于您仅查询一条路线的数据,因此我假设您没有将其存储在缓存或内存中,并且需要在需要路线数据时随时执行此操作。使用优化的查询会更有效,并避免为返回的每一行使用 java 逻辑来清除重复数据。
关于java - JDBC 一对多连接与多选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817833/