java - Java中获取不在数据库中的对象列表的有效方法

标签 java sql

假设我有一个对象列表(ArrayList 对象)和一个对象的数据库表,我想找到尚未存储在数据库中的对象。对象通过它们的“id”来标识。我可以想到两种解决方案,但我不知道哪一种更有效。

我想到的第一个解决方案是构造一个数据库查询来获取数据库中存在的所有对象,并循环遍历存在的对象以确定数据库中不存在的对象

ArrayList<Integer> ids = new ArrayList<Integer>();
for(MyObject o in  objects){
    ids.add(o.getId());
}

//I use sugar orm on Android, raw query can be seen as 
// "select * from my_object where id in [ id1,id2,id3 .....  ]"
List<MyObjectRow> unwanted_objects = MyObject.find("id in (?,?,?,?,.....)",ids);

//remove the query results from the original arraylist
for(MyObjectRow o in  unwanted_objects){
     for(MyObject o1 in  objects){
         if(o1.getId() == o.getId()) objects.remove(o1);

     }
}

第二种解决方案是查询数据库中每个对象是否存在,并将不存在的对象添加到结果数组

ArrayList<MyObject> result_objects = new ArrayList<MyObject>();

boolean exist = false
for(MyObject o in  objects){
       exist = MyObject.find("EXIST( select 1 from my_object where id = ?)", o.getId());
       if(!exist){
           result_objects.add(o);
       }
}

第一种方案只需要一次查询,但是当循环遍历所有找到的对象时,复杂度变成了 O(n*n)

第二种方案构造了n个数据库查询,但复杂度仅为O(n)

就性能而言,哪一个可能更好?

最佳答案

我会使用选项 1 并更改为使用 Map<Integer, MyObject>提高从原始列表中删除查询结果的性能:

List<Integer> ids = new ArrayList<Integer>();
Map<Integer, MyObject> mapToInsert = new HashMap<Integer, MyObject>();
for(MyObject o in  objects) {
    //add the ids of the objects to possibly insert
    ids.add(o.getId());
    //using the id of the object as the key in the map
    mapToInsert.put(o.getId(), o);
}

//retrieve the ids of the elements that already exist in database
List<MyObjectRow> unwanted_objects = MyObject.find("id in (?,?,?,?,.....)",ids);

//remove the query results from the map, not the list
for(MyObjectRow o in unwanted_objects){
     mapToInsert.remove(o.getId());
}

//insert the values that still exist in mapToInsert
Collection<MyObject> valuesToInsert = mapToInsert.values();

关于java - Java中获取不在数据库中的对象列表的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065576/

相关文章:

java - spring boot多行import.sql application.yml配置

java paint(g)、repaint()、update(g) 后端和本地重绘

java - ActionBar 图标中的共享按钮不是默认的。怎么改?

sql - LINQ to SQL 和 SqlDependency

java - Jooq 按日/月/年比较时间戳

mysql - SQL 外部连接场景 - 提出时看起来很简单

sql - 包含开始日期和结束日期的团体价格

java - Apache HttpClient - 内存不足问题

java - Time4j:显示一年中的所有天

sql - 如何在 sql 2005 或 2008 中使列区分大小写