這是我的事件物體。
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Events {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long eventId;
@NotBlank(message = "Please Add Event name ")
@Length(max =100 ,min =2)
private String eventName ;
private String eventDescription;
// Each event is going to be mapped to a Location
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(
name = "location_id",
referencedColumnName = "locationId"
)
@NotNull
private Location location ;
@Temporal(TemporalType.DATE)
Date eventStartDate;
@Temporal(TemporalType.DATE)
Date eventEndDate;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(
name = "category_id",
referencedColumnName = "categoryId"
)
@NotNull
private Categories categories;
}
在我的控制器中,我可以訪問 locationId 和 categoryId 作為請求引數。我不知道如何定義我的 eventsRepository 以通過 locationId 和 categoryId 訪問。我應該對這個 repo 進行哪些更改才能正常作業。
@Repository
public interface EventsRepository extends JpaRepository<Events,Long> {
public Events findByCateoryAndLocation()
}
uj5u.com熱心網友回復:
我認為您需要進行一些調整才能擺脫這個問題。查詢構建器使用實際的列名,因此如果您的列名是 locationId,則使用 'findByLocationId(Integer locationId)' 作為原型。并且請確保物體名稱適合表名稱。
@Repository
public interface EventRepository extends JpaRepository<Event, Integer>
{
Event findByLocationIdAndCategoryId(Integer locationId, Integer categoryId);
}
這是題外話,但我想提一下,請不要在物體類中使用 Lombok。Getter、setter 和構造生成器都可以,但是如果使用延遲初始化,hascode 和字串生成器將很危險。您可能無法從延遲加載中獲益。
uj5u.com熱心網友回復:
您有兩種方法可以讓 jpa-query 作業:
修改您的 JPA 查詢:
@Repository
public interface EventsRepository extends JpaRepository<Events,Long> { public Events findByCateories_IdAndLocation_id(Long categoriesId, long locationId) }
- 使用自定義查詢 - 使用 @Query 注釋您的 jpa 并使用本機查詢
我這邊還有一點要補充。為您的課程命名。您正在使用與業務邏輯沖突的復數 - 特別是與資料庫關系(請參閱事件到類別)。我會使用單數(事件,類別)
uj5u.com熱心網友回復:
這正是我在本機查詢的幫助下解決此問題的方法。
@Query(
value = "SELECT * FROM events where category_id = ?1 AND location_id = ?2",
nativeQuery = true
)
public List<Events> findByCategoryIdAndLocationIdIn(Long CategoryId , Long LocationId);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369935.html
