我有一张桌子,我保存不同的汽车,在价格表中,我将价格的历史保存到卖家所在地区的汽车所依据。 它运作得很好,但是我怎么能只为这辆车的价格历史买卖所有车?
车牌表
@Entity
@Table(name = "car")
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String numberPlate;
private String carName;
...
@Lob
@Column(columnDefinition="mediumblob")
private byte[] image;
private float lastPrise;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "car")
private List<ProductPrice> carPrices;
}
价格表
@Entity
@Table(name = "price")
@EntityListeners({ProductPrice.WritableEntityListener.class})
public class CarPrice {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
private Date created;
@Column(nullable = false)
private String createdBy;
private float price;
@OneToOne
private Region region;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "car_id", nullable = false)
private Car car;
private Date priceDate;
private Date priceDateFrom;
private Date priceDateTo;
}
地区表
@Entity
@Table(name = "region")
public class Region {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long regionId;
private String regionName;
}
我如何获得某个地区的所有汽车(按地区ID)。
如果我使用以下sql语句,我会得到一个我期望的结果
SELECT DISTINCT DATE(pp.priceDate) AS datePrice, c.id, c.CarName, c.numberPlate, c.description, c.lastPrise, pp.price, g.name, pp.grocery_id
FROM car p, region g
JOIN price pp
WHERE
c.id=pp.product_id
AND pp.region_id=g.id
AND pp.region_id=570
ORDER BY c.name, pp.region_id, datePrice;
但是如何使用CriteriaBuilder构建它。
下一个代码段显示了我的解决方案,但我不仅获得了所选region_id的价格历史记录,还获得了所有地区的价格历史记录。
public List<Car> getCarAndLatestPrice(Long id) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Car> qry = cb.createQuery(Car.class);
Root<Car> car = qry.from(Car.class);
//Root<Region> region = qry.from(Region.class);
Join<Car, ProductPrice> price = car.join("productPrices");
qry.distinct(true);
qry.select(car);
qry.orderBy(cb.asc(car.get("name")));
List<Predicate> conditions = new ArrayList<>();
conditions.add(cb.equal(price.get("region"), id));
TypedQuery<Car> typedQuery = getEntityManager().createQuery(qry
.select(car)
.where(conditions.toArray(new Predicate[]{}))
.distinct(true));
List<Car> productList = typedQuery.getResultList();
return productList;
}
也许有人有类似的问题,可以提供我的解决方案。