Using DISTINCT keyword in JPA on individual columns

隐身守侯 提交于 2019-12-31 01:00:18

问题


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.


回答1:


two ways I come up with your problem:

  1. "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.

  2. 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




回答2:


In my opinion a better approach is to return a more specific object holding only the columns you're interested in. See also following answer:

JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped

According to your example you could create a new Object with only the columns you are interested in:

SELECT DISTINCT new com.mypackage.MyInterestingAnnouncement(annoucement.x, annoucement.y, annoucement.z) FROM Announcment annoucement


来源:https://stackoverflow.com/questions/9231118/using-distinct-keyword-in-jpa-on-individual-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!