Skip to main content

Using DISTINCT keyword in JPA on individual columns



I am reading some values from a database that is horribly un-normalized (which I can't control). The call retrieves announcements for university departments, and if a user is in multiple departments (which is possible), then the same results are returned multiple times for these users. However, some departments might have different announcements, while some have the same.





Is there a way for me to use the DISTINCT keyword in JPA on individual columns? This is what I currently have for the query:







String jpql = "SELECT DISTINCT annoucement FROM Announcment announcement "

+ "WHERE (announcement.date <= :now AND announcement.endDate >= :now) "

+ "AND announcement.approved = true AND announcement.departmentId IN (:departmentIDs)";



TypedQuery<Announcement> query = entityManager.createQuery(jpql,

Announcement.class);

query.setParameter("now", new Date());

query.setParameter("departmentIDs", departmentIDs);







The departmentID value might be different, but the announcement, dates, etc. are all identical. This query returns announcements that have duplicate values.


Comments

  1. two ways I come up with your problem:


    "select distinct annoucement.x, annoucement.y, annoucement.z
    ...(without depId) from..."

    then construct an announcement. but you
    lost the persistent object and its references. you have to load them
    again by your Dao objects if you need.
    override equals() [hashCode() too] in your Annoucement class, of
    course, in equals(), depId should be out of the comparison. getting
    the list as you did, then convert the list to Set. you got
    "Distinct" objects


    hope it helps

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.