Okay, so I have several tables
- Vote
- Contest
- ContestSegment
- ContestRegistration
- Submittable
- User
The relationship is that a Submittable may be submitted to a contest via creating a ContestRegistration, which is tied to a ContestSegment, which is tied to a Contest.
A Vote has a User and a reference to a ContestRegistration that the Vote relates to.
Pretty simple.
Now, the idea is that I want to hit a RESTful service which checks to see if I’ve already voted on one of the ContestRegistrations in a contest.
Everything is working except for the desired result.
The JPQL that I’m running looks like this:
SELECT DISTINCT v
FROM Vote v, Contest c
JOIN v.user vu
LEFT JOIN c.segments cs
LEFT JOIN cs.registrations csr
LEFT JOIN csr.votes csrv
WHERE vu.id = :userId
AND cs.beginDate < CURRENT_TIMESTAMP
AND cs.endDate > CURRENT_TIMESTAMP
AND c.id = :contestId
The method looks like:
public Boolean hasUserVoted(User user, Contest contest){
StringBuffer query = new StringBuffer()
.append("SELECT DISTINCT v from Vote v, Contest c ")
.append("JOIN v.user vu LEFT JOIN c.segments cs LEFT JOIN cs.registrations csr LEFT JOIN csr.votes csrv ")
.append("WHERE vu.id = :userId ")
.append(" ")
.append("AND cs.beginDate < CURRENT_TIMESTAMP AND cs.endDate > CURRENT_TIMESTAMP AND c.id = :contestId ");
Boolean hasVoted = true;
try{
Vote vote = (Vote)entityManager.createQuery(query.toString())
.setParameter("userId", user.getId())
.setParameter("contestId", contest.getId()).getSingleResult();
}catch(NoResultException nre){
hasVoted = false;
}
return hasVoted;
}
But when I return, no matter what I plug in, I’m always getting a true back (meaning I’ve already voted). For instance, I’ve voted on contest#1, but I haven’t voted on contest#2. If I plug in the value for contest#2, then I still get a true back. I’m fairly new to JPQL, so any help you can provide would be awesome! Thanks!
With the use of left joins in your JPQL, it will return true unless the contest don’t exists. Its sounds like the csr.votes should be a normal join.