【问题标题】:SpringBoot JPA Interface's save() and delete() not working with ArrayList or LongSpring Boot JPA 接口 save() 和 delete() 不适用于 ArrayList 或 Long
【发布时间】:2018-09-12 06:41:06
【问题描述】:

我正在关注使用 SpringBoot 1.3 的教程。我正在使用最新版本的 SpringBoot 2.0。我正在创建一个 REST API。我需要帮助将 1.3 代码调整为 2.0 合规性,因为 save()delete() 现在期望对象超过 long ids。 我需要如何重写接口才能接受long id' and 'ArrayList

代码如下:

基础对象

@Entity
public class HotelBooking {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id; // could be Long

private String hotelName;
private double pricePerNight;
private int nbOfNights;

public HotelBooking(){} 

public HotelBooking(String hotelName, double pricePerNight, int nbOfNights) {
    this.hotelName = hotelName;
    this.pricePerNight = pricePerNight;
    this.nbOfNights = nbOfNights;
}
// getters omitted
}

界面

@Repository
public interface BookingRepository extends JpaRepository<HotelBooking, Long> {
data/jpa/docs/2.1.0.M1/reference/html/
    List<HotelBooking> findByPricePerNightLessThan(double price);
}

使用long id 删除database 中的条目

@RequestMapping(value = "/delete/id")
public List<HotelBooking> remove(@PathVariable long id) {
    bookingRepository.delete(id);
    return bookingRepository.findAll();
}

尝试将 ArrayList 对象保存到 database

 @Override
    public void run(String... strings) throws Exception {

        List<HotelBooking> bookings = new ArrayList<>();

        bookings.add(new HotelBooking("Marrior", 200.50, 3));
        bookings.add(new HotelBooking("Ibis", 90, 4));
        bookings.add(new HotelBooking("Novotel", 140.74, 1));

        bookingRepository.save(bookings);
    }

问题

上述内容不再适用于 SpringBoot 2.0。 尝试通过 ID 删除时我收到一条错误消息 - Error:(61, 34) java: incompatible types: long cannot be converted to romaniancoder.booking.HotelBooking 它现在期待一个对象而不是 long id 在数据库中找到一个对象。

尝试保存 ArrayList 时出现此错误 - Error:(40, 26) java: method save in interface org.springframework.data.repository.CrudRepository<T,ID> cannot be applied to given types; required: S found: java.util.List<romaniancoder.booking.HotelBooking> reason: inferred type does not conform to upper bound(s) inferred: java.util.List<romaniancoder.booking.HotelBooking> upper bound(s): romaniancoder.booking.HotelBooking 就好像它需要一个扩展的类或其他东西才能工作?我不确定...

阅读 Spring Docs 后,我不明白为什么会发生这种变化,以及如何编写代码来接受 long id 以在 database 中查找内容。我不明白如何让save() 接受ArrayLists

【问题讨论】:

  • 您可以使用repository.deleteById(Long) 和repository.saveAll(ArrayList)。
  • 非常感谢,这正是我需要的答案。我自己在哪里可以找到这个?我还没有找到列出 SpringBoot 的所有可用功能的文档。
  • 这些变化是在 SpringBoot 2.0 中引入的,IDE 自动补全显示了这些新方法。

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


【解决方案1】:

您可以使用repository.deleteById(Long)repository.saveAll(ArrayList)。这些方法是在 SpringBoot 2.0 中引入的。

【讨论】:

猜你喜欢
  • 2021-03-01
  • 2022-12-05
  • 2016-07-12
  • 2016-12-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2017-11-13
  • 1970-01-01
相关资源
最近更新 更多