找出数据库条目和存储在应用程序中的条目之间的休眠差异的最快方法
Fastest way to find out in hibernate diff between database entries and entries stored within app
@Entity
Student {
Long id;
String name;
}
假设我有一个 10 名学生的列表 List<Student> studentList = new ArrayList<>();
存储在我的应用程序某处的列表中。
我有一个列表,其中包含我之前存储在数据库中的 20 个实体:
List<Student> studentsDbList = StudentRepo.findAll()
我想找出这 20 个中有哪些不在 studentList 中,并以最有效的方式将它们从数据库中删除,而不用清除整个数据库。
我在 hibernate 上找不到任何类似的东西,它允许我通过一个方法调用来做到这一点,但我认为这是一个微不足道的问题,已经解决了很多次,而且我根本不理解 hibernate 足以用一些 oneliner 解决它(
这里有什么建议吗?
您可以过滤不在应用程序中的数据库实体,并使用 Stream 获取要删除的那些学生的 ID API
List<Long> ids = studentsDbList.stream()
.filter(e -> !studentList.contains(e))
.map(e -> e.getId())
.collect(Collectors.toList());
然后通过在存储库上使用它按 ID 从数据库中删除
void deleteByIdIn(List<Long> ids);
然后打电话给你要删除的那些学生id
studentRepo.deleteByIdIn(ids);
注意: 覆盖学生 class
另一种更好的方法是
List<Long> ids = studentList.stream()
.map(e -> e.getId())
.collect(Collectors.toList());
@Query(value = "DELETE FROM Student s WHERE s.id NOT IN (:ids)")
void deleteByIdIn(@Param("ids") List<Long> ids);
findAll() 似乎不是最佳方式,它是一种代码味道。我只会从数据库中获取 id。将此方法添加到学生存储库:
@Query("select s.id from Student s")
List<Long> getAllIds();
void deleteByIdIn(List<Long> ids);
然后对 id 的列表进行差异化处理并按 ids 删除:
ArrayList<Long> studentIdsToRemove = new ArrayList<>(studentIdsFromDB);
studentIdsToRemove.removeAll(studentIds);
studentRepo.deleteByIdIn(studentIdsToRemove);
@Entity
Student {
Long id;
String name;
}
假设我有一个 10 名学生的列表 List<Student> studentList = new ArrayList<>();
存储在我的应用程序某处的列表中。
我有一个列表,其中包含我之前存储在数据库中的 20 个实体:
List<Student> studentsDbList = StudentRepo.findAll()
我想找出这 20 个中有哪些不在 studentList 中,并以最有效的方式将它们从数据库中删除,而不用清除整个数据库。
我在 hibernate 上找不到任何类似的东西,它允许我通过一个方法调用来做到这一点,但我认为这是一个微不足道的问题,已经解决了很多次,而且我根本不理解 hibernate 足以用一些 oneliner 解决它(
这里有什么建议吗?
您可以过滤不在应用程序中的数据库实体,并使用 Stream 获取要删除的那些学生的 ID API
List<Long> ids = studentsDbList.stream()
.filter(e -> !studentList.contains(e))
.map(e -> e.getId())
.collect(Collectors.toList());
然后通过在存储库上使用它按 ID 从数据库中删除
void deleteByIdIn(List<Long> ids);
然后打电话给你要删除的那些学生id
studentRepo.deleteByIdIn(ids);
注意: 覆盖学生 class
另一种更好的方法是
List<Long> ids = studentList.stream()
.map(e -> e.getId())
.collect(Collectors.toList());
@Query(value = "DELETE FROM Student s WHERE s.id NOT IN (:ids)")
void deleteByIdIn(@Param("ids") List<Long> ids);
findAll() 似乎不是最佳方式,它是一种代码味道。我只会从数据库中获取 id。将此方法添加到学生存储库:
@Query("select s.id from Student s")
List<Long> getAllIds();
void deleteByIdIn(List<Long> ids);
然后对 id 的列表进行差异化处理并按 ids 删除:
ArrayList<Long> studentIdsToRemove = new ArrayList<>(studentIdsFromDB);
studentIdsToRemove.removeAll(studentIds);
studentRepo.deleteByIdIn(studentIdsToRemove);