I am following a tutorial that uses SpringBoot 1.3. I am on the latest release of SpringBoot 2.0. I am working on creating an REST API. I need help adapting the 1.3 code to 2.0 compliance as save() and delete() now expect objects over long ids. How do I need to rewrite the interface to accept long id' and 'ArrayList?
Here's the code as it stands:
@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 to delete an entry in the database
@RequestMapping(value = "/delete/id")
public List<HotelBooking> remove(@PathVariable long id) {
bookingRepository.delete(id);
return bookingRepository.findAll();
}
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);
}
The above do not work in SpringBoot 2.0 anymore. When trying to delete via ID I get an error saying - Error:(61, 34) java: incompatible types: long cannot be converted to romaniancoder.booking.HotelBooking
It is now expecting an object instead of a long id to find an object in the database.
When trying to save an ArrayList I get this error - 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
It's as if it needs a class extended or something to work? I am not sure...
After reading the Spring Docs I don't understand why this changed and how I can write code to accept a long id to find something in the database. I don't understand how to adapt save() to accept ArrayLists.
You can use repository.deleteById(Long) and repository.saveAll(ArrayList). These methods are introduced in SpringBoot 2.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With