[英]spring boot repository: check if Date exists
在我的預訂實體中,我有一列“bookingDate”-> 示例:“2021-05-10 12:00:00”。
所以在這個 object 中顯示了用戶預訂的日期和開始時間。
如果用戶想預訂時間段,我想先檢查所選時間段是否為空。 所以我想按日期和開始時間查詢數據庫。
我用https://www.baeldung.com/spring-data-jpa-query-by-date試過,但沒有用。 我收到錯誤消息:“此位置不允許使用注釋 @Temporal”和“@Temporal 不能用於變量”
這些是相關的類:
預訂。java
@Entity
public class Reservation {
@Id @GeneratedValue
private int reservationId;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime bookingDate;
private int court = 1;
private String playerNames;
private int userIdReservation;
//getter and setters
使用方法“findByBookingDate()”我想查詢數據庫,如果選擇的時間段是空的......
驗證類.java
public boolean validateReservation(Reservation r) {
LocalDateTime tempDate = r.getBookingDate();
if(reservationRepository.findByBookingDate(tempDate)){ // todo: + and Court
logger.getLogger().info(this.getClass().getName() + "||Booking Slot is empty -- Reservation created||");
return true;
}
logger.getLogger().info(this.getClass().getName() + "||Booking Slot is full -- Reservation failed||");
return false;
}
ReservationRepository.java
@Repository
@Repository
public interface ReservationRepository extends JpaRepository<Reservation, Integer>{
@Query("Select r from reservation r where r.booking_date = :tempDate")
boolean findByBookingDate(@Param("tempDate") LocalDateTime tempDate);
}
如果我像這樣運行它,我總是得到一個“org.springframework.beans.factory.UnsatisfiedDependencyException:創建名稱為'backyardcodersSpringReactApplication'的bean時出錯” - >所以應用程序沒有成功啟動。
我非常感謝每一個提示和批評!
干杯!
完全沒看懂。 這只是一個線索,也許不是一個完美的解決方案。
您可以使用 java.time.LocalDateTime。 和注釋就像@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)。
查詢應該是這樣的。 [查詢將檢查當天的所有預訂]
來自 reservation_table 的 Select 其中時隙在“2021-05-10 00:00:00”和“2021-05-10 23:59:59”之間
我將您的代碼復制到我的本地文件中。 代替
導入 org.springframework.data.jpa.repository.Temporal;
我用了
導入 javax.persistence.Temporal;
在您的Reservation.java
文件中。
這也是我在 Stackoverflow 上的第一個答案。
首先@Temporal
有三個不同的 arguments 並且可以應用於日期、時間和時間戳類型的變量。
用法
@Temporal(Temporal type.DATE)
private Date date;
@Temporal(Temporal type.TIMESTAMP) // INSERT BOTH DATE WITH TIME TILL MILLISECONDS
private Calendar date;
為什么不直接從 LocalDateTime 中提取 localdate 並將其傳遞? 並提取小時並將其傳遞並用它查詢2個不同的列。
LocalDateTime.toLocalDate()
LocalDateTime.getHour()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.