我在Repository interfase和DatabaseSeeder中存在一些泛型问题 当我启动服务器时出现错误"推断类型不符合上限(#);和hotelRepository.save(预订)下划线。有人可以帮我解决这个问题吗?
实体
@Entity
public class HotelBooking {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String hotelName;
private double pricePerNight;
private int nbOfNights;
public HotelBooking(String hotelName, double pricePerNight, int nbOfNights){
this.hotelName = hotelName;
this.pricePerNight = pricePerNight;
this.nbOfNights = nbOfNights;
}
public HotelBooking() {
}
public String getHotelName() {
return hotelName;
}
public double getPricePerNight() {
return pricePerNight;
}
public int getNbOfNights() {
return nbOfNights;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public void setPricePerNight(double pricePerNight) {
this.pricePerNight = pricePerNight;
}
public void setNbOfNights(int nbOfNights) {
this.nbOfNights = nbOfNights;
}
public long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
控制器
@RestController
@RequestMapping(value = "/bookings")
public class HotelController {
HotelRepository hotelRepository;
@Autowired
public HotelController(HotelRepository hotelRepository){
this.hotelRepository = hotelRepository;
}
@RequestMapping(value = "/all", method = RequestMethod.GET)
public List<HotelBooking> getAll(){
return hotelRepository.findAll();
}
@RequestMapping(value = "/affordable/{price}", method = RequestMethod.GET)
public List<HotelBooking> getAffordable(@PathVariable double price){
return hotelRepository.findByPricePerNightLessThan(price);
}
@RequestMapping(value ="/create", method = RequestMethod.POST)
public List<HotelBooking> create(@RequestBody HotelBooking hotelBooking){
hotelRepository.save(hotelBooking);
return hotelRepository.findAll();
}
@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
public List<HotelBooking> remove(@PathVariable Long id){
hotelRepository.deleteById(id);
return hotelRepository.findAll();
}
}
组件类
@Component
public class DatabaseSeeder implements CommandLineRunner {
private HotelRepository hotelRepository;
@Autowired
public DatabaseSeeder(HotelRepository hotelRepository){
this.hotelRepository = hotelRepository;
}
@Override
public void run(String... strings) throws Exception {
List<HotelBooking> bookings = new ArrayList<>();
bookings.add(new HotelBooking("Marriot", 200.5, 3));
bookings.add(new HotelBooking("Ibis", 300.5, 4));
bookings.add(new HotelBooking("Novotel", 100.5, 1));
hotelRepository.save(bookings);
}
}
存储库类
@Repository
public interface HotelRepository extends JpaRepository<HotelBooking, Long> {
List<HotelBooking> findByPricePerNightLessThan(double price);
}
答案 0 :(得分:0)
您应该使用hotelRepository.saveAll(bookings);
代替hotelRepository.save(bookings);
答案 1 :(得分:0)
仅添加了先前的答案: 如果您使用spring-boot 1.5,则您的代码应该工作,但是在2.0中,spring数据CrudRepository的API的实现已更改,现在您应该使用saveAll保存可迭代对象。
如果要在一个saveAll请求中保存更多数据,还应该考虑配置批处理请求。 https://vladmihalcea.com/the-best-way-to-do-batch-processing-with-jpa-and-hibernate/