引用表中的JpaRepository findBy字段

时间:2018-07-09 12:43:21

标签: java spring-boot spring-data-jpa jpql

@Entity
@Table(name="seance")
@Data
public class Seance {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer id;

    private java.time.LocalTime displayTime;

    @ManyToMany(mappedBy = "seances")
    @JsonIgnore
    private List<Repertoire> repertoires = new ArrayList<>();

    @OneToMany(mappedBy = "reservationSeance", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonIgnore
    private List<Reservation> reservations = new ArrayList<>();

}


@Entity
@Table(name="reservation")
@Data
public class Reservation {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer id;

    private java.time.LocalDate reservationDate;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "id_seance")
    private Seance reservationSeance;

   .........

}

我有两个与ManyToOne有关的实体,我尝试扩展JpaRepository

public interface ReservationRepository extends JpaRepository<Reservation,Integer> {
    List<Reservation> findReservationsByReservationSeance(Seance seance);
}

但是作为参数,我必须使用所有对象Seance,是否可以使用JpaRepository仅通过Seance表中的id和displayTime查找保留,还是需要编写自己的方法?

1 个答案:

答案 0 :(得分:2)

您可以在ReservationRepository

中添加自己的查询
@Query("SELECT r FROM Reservation r WHERE r.reservationSeance.id=:seanceId AND r.reservationSeance.displayTime = :displayTime")
public List<Reservation> findReservations(@Param("seanceId") int seanceId, @Param("displayTime") LocalTime displayTime);