Click here to Skip to main content
15,904,416 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
The car class will be inherited by several others, it needs to filter all attributes and method results. Can someone give me a hint how to do this?
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "APP_CAR")
@Entity
public abstract class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String type;
    private Double length;
    @CreatedBy
    private String createdBy;
    @CreatedDate
    private LocalDateTime createdAt;

    public abstract Double averageSpeed();
    public abstract Double averageFuelConsumption();
}


What I have tried:

I tried crtieria and QueryDSL
@NamedQuery(
    name = "Shape.findByArea",
    query = "SELECT s FROM Shape s WHERE s.getArea BETWEEN :minArea AND :maxArea"
)

@NamedQuery(
    name = "Shape.findByPerimeter",
    query = "SELECT s FROM Shape s WHERE s.getPerimeter BETWEEN :minPerimeter AND :maxPerimeter"
)

public List<Shape> getShapesByArea(double minArea, double maxArea) {
    return entityManager.createNamedQuery("Shape.findByArea", Shape.class)
        .setParameter("minArea", minArea)
        .setParameter("maxArea", maxArea)
        .getResultList();
}

public List<Shape> getShapesByPerimeter(double minPerimeter, double maxPerimeter) {
    return entityManager.createNamedQuery("Shape.findByPerimeter", Shape.class)
        .setParameter("minPerimeter", minPerimeter)
        .setParameter("maxPerimeter", maxPerimeter)
        .getResultList();
}


public List<Shape> getShapesByArea(double minArea, double maxArea) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Shape> criteria = builder.createQuery(Shape.class);
    Root<Shape> root = criteria.from(Shape.class);

    criteria.where(
        builder.between(root.get("getArea"), minArea, maxArea)
    );

    return entityManager.createQuery(criteria).getResultList();
}

public List<Shape> getShapesByPerimeter(double minPerimeter, double maxPerimeter) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Shape> criteria = builder.createQuery(Shape.class);
    Root<Shape> root = criteria.from(Shape.class);

    criteria.where(
        builder.between(root.get("getPerimeter"), minPerimeter, maxPerimeter)
    );

    return entityManager.createQuery(criteria).getResultList();
}
Posted
Updated 7-Feb-23 20:55pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900