我目前已經製作了一個用於事件系統的彈簧啟動項目。在預訂課程的模型中,我有兩個對象,一個是事件,另一個是用戶。現在我想創建一個 get 請求,允許我分別獲取單個用戶的所有預訂和單個事件的所有預訂。我設法創建了其他請求,這些請求正在獲取所有預訂並通過預訂 ID 進行預訂。
現在,如果我嘗試創建任何類型的實現,它要么給我一個空指針錯誤,要么告訴我表關係“預訂”不存在。請讓我知道是否可以編寫這樣的獲取請求。謝謝
模型:
@Id
@SequenceGenerator(
name = "booking_sequence",
sequenceName = "booking_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "booking_sequence"
)
private Long id;
@ManyToOne
@JoinColumn(
name = "event_id",
referencedColumnName = "id"
)
private Event event;
@ManyToOne
@JoinColumn(
name = "user_id",
referencedColumnName = "id"
)
private User user;
private Integer tickets;
@Transient
private Integer amount;
存儲庫:
@Repository
public interface BookingRepository extends JpaRepository<Booking, Long > {
@Query
Optional<Booking> findBookingById(Long id);
}
服務:
@Autowired
public BookingService(BookingRepository bookingRepository) {
this.bookingRepository = bookingRepository;
}
public List<Booking> getBookingList() {
return bookingRepository.findAll();
}
public Booking getSingleBooking(Long bookingId) {
return bookingRepository.findBookingById(bookingId).orElseThrow();
}
控制器:
@GetMapping
public List<Booking> getBookings() {
return bookingService.getBookingList();
}
@GetMapping(path = "{bookingId}")
public Booking getSingleBooking(@PathVariable("bookingId") Long bookingId) {
return bookingService.getSingleBooking(bookingId);}
@GetMapping(path = "/user/{userId}")
public List<Booking> getUserBookings(@PathVariable("userId") Long userId) {
return bookingService.getBookingByUser(userId);}
@GetMapping(path = "/event/{eventId}")
public List<Booking> getEventBookings(@PathVariable("eventId") Long eventId) {
return bookingService.getBookingForEvent(eventId);}
所以有可能提出這樣的請求,我所做的只是使用“nativeQuery”,以便它按照我想要的方式運行。如前所述,我想發出兩個獲取請求,這是我為它們編寫查詢的方式。
使用其“ID”獲取特定用戶的所有用戶預訂:
@Query(value = "SELECT * from bookings, user where bookings.user_id = :id", nativeQuery = true)
List<Booking> findByUserid(Long id);
使用其“ID”獲取特定事件的所有事件預訂:
@Query(value = "SELECT * from bookings, user where bookings.event_id = :id", nativeQuery = true)
List<Booking> findByEventid(Long id);
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen