Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在hibernate中查找数据库条目和应用程序中存储的条目之间差异的最快方法_Java_Postgresql_Hibernate_Entity - Fatal编程技术网

Java 在hibernate中查找数据库条目和应用程序中存储的条目之间差异的最快方法

Java 在hibernate中查找数据库条目和应用程序中存储的条目之间差异的最快方法,java,postgresql,hibernate,entity,Java,Postgresql,Hibernate,Entity,假设我有一个10名学生的列表list studentList=new ArrayList()存储在我的应用程序的某个列表中 我在DB中存储了20个实体的列表: @Entity Student { Long id; String name; } List studentsDbList=StudentRepo.findAll() 我想找出这20个中的哪一个不在学生名单中,并以最有效的方式将其从数据库中删除,而无需清除整个数据库。 我在hibernate上找不到类似的东西,它允许我用一

假设我有一个10名学生的列表
list studentList=new ArrayList()存储在我的应用程序的某个列表中

我在DB中存储了20个实体的列表:

@Entity
Student {
  Long id;
  String name;  
}
List studentsDbList=StudentRepo.findAll()
我想找出这20个中的哪一个不在学生名单中,并以最有效的方式将其从数据库中删除,而无需清除整个数据库。
我在hibernate上找不到类似的东西,它允许我用一个方法调用来实现这一点,但我认为这是一个已经解决了无数次的小问题,我只是对hibernate的理解不够,无法用一行程序来解决它(
这里有什么建议吗?

您可以筛选应用程序中未包含的数据库实体,并使用Stream API获取要删除的学生的id

List<Student> studentsDbList = StudentRepo.findAll()
注意:在学生课堂上覆盖等于

另一个更好的方法是

studentRepo.deleteByIdIn(ids);
List id=studentList.stream()
.map(e->e.getId())
.collect(Collectors.toList());
@查询(value=“从学生s中删除,其中s.id不在(:id)”)
void deleteByIdIn(@Param(“ids”)列表id);
findAll()似乎不是最佳方式,而且是一种代码味道。我只会从数据库中获取id。将此方法添加到学生存储库:

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);
@Query(“从学生s中选择s.id”)
列出getAllID();
void deleteByIdIn(列表ID);
然后在id列表上进行区分并按id删除:

@Query("select s.id from Student s")
List<Long> getAllIds();

void deleteByIdIn(List<Long> ids);
ArrayList studentIdsToRemove=新的ArrayList(studentIdsFromDB);
studentIdsToRemove.removeAll(studentIds);
studentRepo.deleteByIdIn(studentstoremove);

Btw,为什么要使用id?存储完整实体有什么区别?内存?实际上根本不存储id,让id删除它们。并且不能按实体删除它们,这就是为什么添加另一个解决方案应该有效的原因
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);
@Query("select s.id from Student s")
List<Long> getAllIds();

void deleteByIdIn(List<Long> ids);
ArrayList<Long> studentIdsToRemove = new ArrayList<>(studentIdsFromDB);
studentIdsToRemove.removeAll(studentIds);
studentRepo.deleteByIdIn(studentIdsToRemove);