Hall.java
@Entity
@Table(name="halls")
public class Hall {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "Hall name should be provided.")
private String name;
@NotNull
@Min(value = 1, message = "Price must be greater than zero.")
private Integer basicPrice;
@NotNull
@Min(value = 1, message = "capacity must be greater than zero.")
private Integer capacity;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id")
private City city;
// Other fields, constructor, getters and setters removed
}
City.java
@Entity
@Table(name="cities")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String cityName;
@OneToMany(mappedBy="city", fetch=FetchType.LAZY)
private List<Hall> halls;
// Other fields, constructor, getters and setters removed
}
I would like to let a user search halls based on filters in the front end. If a user passes a city it should return halls in that city regardless of price and capacity. The user can also search for halls with prices in a range. I have tried the following
HallRepo.java
@Repository
public interface HallRepo extends CrudRepository<Hall, Long> {
@Query(value = "SELECT * FROM halls JOIN cities ON cities.id = halls.city_id WHERE "
+ "(cities.city_name = :cityName OR :cityName IS null) "
+ "AND (halls.basic_price BETWEEN :minP AND :maxP OR (:minP IS null AND :maxP IS null)) "
+ "AND (halls.capacity BETWEEN :minC AND :maxC OR (:minC IS null AND :maxC IS null))",
nativeQuery = true)
List<Hall> findByQuery(
@Param("cityName") String cityName,
@Param("minP") Integer minPrice,
@Param("maxP") Integer maxPrice,
@Param("minC") Integer minCapacity,
@Param("maxC") Integer maxCapacity);
}
It's not Working. How to do it?