我们正在针对现有数据库编写一个新应用程序。我正在使用 Spring Data JPA,并且只是在做一个
MyRepository.save()
在我的新实体上,使用
MyRepository extends CrudRepository<MyThing, String>
我在日志中注意到 hibernate 在插入之前执行了一个 Select 操作,并且它们需要很长时间,即使在使用索引时也是如此。
我在这里搜索过这个,answers I've found通常与 Hibernate 相关。我对 JPA 很陌生,看起来 JPA 和 Hibernate 非常紧密地交织在一起,至少在 Spring Data 的上下文中使用它时是如此。链接的答案建议使用 Hibernate persist(),或者以某种方式使用 session ,可能来自 entityManager?我不必直接对 session 或实体管理器或任何 Hibernate API 做任何事情。到目前为止,我已经在我的存储库中使用 save() 和几个 @Query 完成了简单的插入操作。
最佳答案
这是您使用 Spring Data 存储库使用的 Spring SimpleJpaRepository 的代码:
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
它执行以下操作:
By default Spring Data JPA inspects the identifier property of the given entity. If the identifier property is null, then the entity will be assumed as new, otherwise as not new.
Link to Spring Data documentation
因此,如果您的一个实体的 ID 字段不为空,Spring 将让 Hibernate 进行更新(之前也是 SELECT)。
您可以通过同一文档中列出的 2 种方法来覆盖此行为。一个简单的方法是让您的实体实现 Persistable(而不是 Serializable),这将使您实现方法“isNew”。
关于java - 如何在 save() 之前阻止 spring data JPA 执行 SELECT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45635827/