【问题标题】:Query and Database performance when used with JpaRepository findAll() vs native query using JpaRepository与 JpaRepository findAll() 一起使用时的查询和数据库性能与使用 JpaRepository 的本机查询
【发布时间】:2018-04-20 08:47:32
【问题描述】:

我正在开发一个 Spring Boot 项目,其中我有两个 JPA 函数,我需要确定哪个函数会更好地执行并减少对数据库查询性能的压力并利用 Hibernate 缓存。请指导使用哪个查询。

我的仓库界面:

@Repository
public interface CustomersRepository
        extends JpaRepository<CustomersEntity, Long> {

    @Query(nativeQuery = true, value = "SELECT * FROM customers WHERE c_mobile = ?1")
    CustomersEntity findcustomerByMobile(String mobileNo);

    @Override
    List<CustomersEntity> findAll();
}

我的服务类:

@Scope("request")
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomersRepository customersRepository;

    @Override
    public boolean findCustomerByMobile1(long mobileNo) {

        CustomersEntity customersEntity = customersRepository.findcustomerByMobile(mobileNo);

        if (customersEntity != null)
            return true;
        else
            return false;
    }

    @Override
    public boolean findCustomerByMobile2(long mobileNo) {

        List<CustomersEntity> entityList = customersRepository.findAll();

        for (CustomersEntity entity : entityList) {
            if (entity.getcMobile() == mobileNo) {
                return true;
            }
        }

        return false;
    }
}

【问题讨论】:

  • 绝对是第一个。因为在第二个查询中,所有移动设备都加载到会话中并进入应用程序端,另外数据库必须加载所有不必要的记录。在第一个中,只有一个记录加载到数据库中,我们不需要遍历列表来找到那个 mobileno。我认为如果移动表有许多记录,例如 100000 或更多,第二个查询根本不起作用,另外,在应用程序预热一段时间后,休眠缓存工作正常。
  • 感谢您的解释。

标签: spring hibernate spring-boot jpa spring-data-jpa


【解决方案1】:

无需将数据库中的所有记录下载到您的应用程序然后过滤它们。如果有数千条记录,它会变慢。

相反,您应该在c_mobile 字段上创建一个索引,然后像这个简单的方法一样使用:

public interface CustomerRepo extends JpaRepository<CustomersEntity, Long> {
    CustomersEntity findByMobileNo(String mobileNo);
}

它会在瞬间工作(带索引)。

有关构建查询方法的更多信息,您可以找到here

【讨论】:

    猜你喜欢
    • 2017-01-24
    • 2022-07-26
    • 2015-12-26
    • 1970-01-01
    • 2021-10-16
    • 2017-04-18
    • 2018-09-19
    • 2012-05-25
    • 2021-12-14
    相关资源
    最近更新 更多