【发布时间】: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