如何在save()之前停止弹簧数据JPA执行SELECT? [英] How do I stop spring data JPA from doing a SELECT before a save()?

查看:1627
本文介绍了如何在save()之前停止弹簧数据JPA执行SELECT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在针对现有数据库编写新应用程序。我正在使用Spring Data JPA,并且只是做一个

  MyRepository.save()
 在我的新实体上使用 

MyRepository扩展CrudRepository< MyThing,String>

我在日志中注意到hibernate正在执行Select之前插入,并且它们是需要很长时间,即使使用索引。



我在这里搜索了这个,我找到的答案通常与Hibernate具体相关。我对JPA相当陌生,看起来JPA和Hibernate好像紧密交织在一起,至少在Spring Data的环境中使用它。链接的答案建议使用Hibernate persist(),或者以某种方式使用会话,可能来自entityManager?我没有必须直接使用会话或实体管理器或任何Hibernate API。到目前为止,我已经在我的存储库中使用save()和一对@Query进行了简单的插入。

解决方案

这是使用Spring Data存储库的Spring SimpleJpaRepository代码:

  @Transactional 
public< S extends T> S save(S entity){

if(entityInformation.isNew(entity)){
em.persist(entity);
返回实体;
} else {
return em.merge(entity);


$ $ $
$ b pre $ $ $ $ $ $ $ $ $ $ $
$ b


默认情况下,Spring Data JPA检查给定实体的标识属性。如果标识符属性为空,那么该实体将被视为新的,否则为不新。


链接到Spring Data文档

所以如果你的实体中有一个ID字段不为null,Spring会让Hibernate做一次更新(以及之前的SELECT)。
$ b

您可以通过同一文档中列出的两种方式覆盖此行为。一个简单的方法是让你的实体实现Persistable(而不是Serializable),这将使你实现方法isNew。


We are writing a new app against an existing database. I'm using Spring Data JPA, and simply doing a

MyRepository.save() 

on my new entity, using

MyRepository extends CrudRepository<MyThing, String>

I've noticed in the logs that hibernate is doing a Select before the insert, and that they are taking a long time, even when using the indexes.

I've searched for this here, and the answers I've found usually are related to Hibernate specifically. I'm pretty new to JPA and it seems like JPA and Hibernate are pretty closely intertwined, at least when using it within the context of Spring Data. The linked answers suggest using Hibernate persist(), or somehow using a session, possibly from an entityManager? I haven't had to do anything with sessions or entityManagers, or any Hibernate API directly. So far I've gotten simple inserts done with save() and a couple @Query in my Repositories.

解决方案

Here is the code of Spring SimpleJpaRepository you are using by using Spring Data repository:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

It does the following:

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

And so if one of your entity has an ID field not null, Spring will make Hibernate do an update (and so a SELECT before).

You can override this behavior by the 2 ways listed in the same documentation. An easy way is it to make your Entity implement Persistable (instead of Serializable), which will make you implement the method "isNew".

这篇关于如何在save()之前停止弹簧数据JPA执行SELECT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆