java - 如何使用 Spring Boot 从文件中获取数据列表?

标签 java spring spring-mvc jpa spring-boot

我正在研究这个简单的任务,我的任务是添加一个新的 REST api 我继续创建了一个新的 Controller ,我可以在其中检索 sql 文件中的所有数据。不过,我一直在获取酒店列表。谢谢。

这是我的代码:

Controller :

package sample.data.jpa.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sample.data.jpa.domain.City;
import sample.data.jpa.domain.Hotel;
import sample.data.jpa.domain.HotelSummary;
import sample.data.jpa.domain.Review;
import sample.data.jpa.service.CityService;
import sample.data.jpa.service.CityRepository;
import sample.data.jpa.service.HotelService;

@Controller
class HotelController {

@Autowired(required = true)
private CityRepository cityRepository;

@Autowired(required = true)
private CityService cityService;

private HotelService hotelService;

private City cityObject;
private Hotel hotelObject;

@RequestMapping(value = "/getAllData")
@ResponseBody
@Transactional(readOnly = true)
Iterable<City> getAllData() {
    return this.cityRepository.findAll();
}

@RequestMapping(value = "/new")
@ResponseBody
@Transactional(readOnly = true)
Iterable<Hotel> getBestHotelsWithBestRatings() {
    return this.hotelService.getHotel(cityObject, name);
}

}

最佳答案

我强烈建议忘记从数据库中提取完整的数据集并在应用程序服务器中过滤它。它可能会增加巨大的开销。请记住,与数据库对话的成本很高,您应该优化读取尽可能小的数据集。

您应该在数据库查询中过滤它。因此我建议查看 spring-data-jpa @Query usage .

您的存储库可能如下所示:

public interface HotelRepository extends JpaRepository<Hotel, Long> {

  @Query("select * from Hotel h where h.averageRating > ?1")
  List<Hotel> findAllPopular(int averageRating);
}

关于java - 如何使用 Spring Boot 从文件中获取数据列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843148/

相关文章:

java - 如何在 Spring MVC 的命令对象的列表集合中绑定(bind)一个对象

java - 在什么情况下trimToSize()方法不会影响Java中StringBuffer类的capacity()方法返回的值?

java - 如何用 MyBatis/Spring 实现批量操作?

java - Spring Data neo4j - Id 生成策略

java - 如何在我的自定义 HandlerMethodArgumentResolver 中访问路径变量

java - 无法在 Spring Mavenized 元素中加载 CSS

java - 覆盖主页按钮的功能

java - 为什么我的生产者线程没有完成它的任务?

java - 按开始和结束时间过滤带日期的 ArrayList

Spring Boot/Security - 在嵌入式 Tomcat 上运行时无法自定义安全性