【问题标题】:How to get list of data from a file using Spring Boot?如何使用 Spring Boot 从文件中获取数据列表?
【发布时间】:2016-01-17 20:14:48
【问题描述】:

我正在做这个简单的工作我的任务是添加一个新的 REST api 我继续创建了一个新控制器,我可以在其中从 sql 文件中检索所有数据。但是,我一直在获取酒店列表。谢谢。

这是我的代码:

控制器:

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);
}

}

【问题讨论】:

    标签: java spring spring-mvc jpa spring-boot


    【解决方案1】:

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

    您应该在数据库查询中过滤它。因此,我建议查看 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);
    }
    

    【讨论】:

    • 是的,我和你在一起,这就是为什么我向我的 pom.xml 添加一个新的依赖项,如下所示:
    • com.h2databaseh2runtime
    • 但我的问题仍然悬而未决:(
    • 对不起,我没有关注这些 cmets
    • 顺便说一句,我更新了我的代码示例以匹配问题。我之前搞砸了哪个数据库表。
    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2020-10-27
    • 2016-11-11
    • 2020-07-17
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多