Click here to Skip to main content
15,946,988 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm selecting max id of Dosage entity after join Farmers entity:

Java
cq.select(cb.max(root.get("id")))
.where(cb.equal(root.join("farmers").get("id"), id));




It doesn't return uniqueResult(); but all Farmers instead.

What I have tried:

Java
public Dosage maxDose(int id) {
        try (Session session = sf.openSession()) {
            CriteriaBuilder cb = sf.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Dosage> root = cq.from(Dosage.class);

             cq.select(cb.max(root.get("id"))).where(cb.equal(root.join("farmers").get("id"), id));
            cq.select(root);
            return (Dosage) session.createQuery(cq).uniqueResult();
        }
    }  


I've solved by :

public int maxDate(int id) {
    try (Session session = sf.openSession()) {
        return (int) session.createQuery("SELECT max(d.id) FROM Dosage d, Farmers f WHERE f.id = " + id).uniqueResult();
    }
}


But how to accomplish using JPA criteria?
Posted
Updated 18-Feb-21 6:06am
v4

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