我正在研究这个简单的任务,我的任务是添加一个新的 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/