我使用Spring Data JPA并且有两个参与者:
@Entity
@Data
@Table(name="vehicle_entity")
public class Vehicle {
@Id
@GeneratedValue
private Integer id;
private String type;
private String vehicleRegNumber;
@OneToMany(targetEntity = com.transport.model.BookedTime.class, fetch=FetchType.EAGER)
@JoinColumn(name="bookingTime", referencedColumnName="id")
Set<BookingTime> bookingTime;
}
和
@Entity
@Data
@Table(name="booked_time")
public class BookedTime {
@Id
@GeneratedValue
Integer id;
Long startPeriod;
Long finishPeriod;
}
和存储库:
public interface VehicleRepository extends JpaRepository<Vehicle, Integer> {
@Query("correct query")
List<Vehicle> findAllByPeriod(@Param("startPeriod") int startPeriod, @Param("endPeriod") int endPeriod);
}
我需要找到availbale车辆,没有按时间预订。有谁知道我该怎么做。
答案 0 :(得分:2)
我会选择类似的东西:
@Query(nativeQuery=true, value = "select * from vehicle_entity v join booked_time b on b.vehicle = v.id where not (b.startPeriod > :startPeriod and b.endPeriod < :endPeriod)"
BTW我认为您可能想尝试将EAGER
的FetchType更改为LAZY
bookingTime
,然后在选择查询中使用join fetch
。
答案 1 :(得分:0)
所以我找到了几个解决我问题的方法。第一个是由Enigo提供的,第二个是由
提供的 @Query(nativeQuery = false, value = "select v from Vehicle v right join fetch v.bookedTime b \n" +
"Where b.vehicle = v.id " +
"AND (b.startPeriod < :startPeriod OR b.startPeriod > :finishPeriod) " +
"AND (b.finishPeriod < :startPeriod OR b.finishPeriod > :finishPeriod)")
Set<Vehicle> findAllByPeriod(@Param("startPeriod") Long startPeriod, @Param("finishPeriod") Long finishPeriod);