简体   繁体   中英

Java/JPA Select unique entities

I'm using JPA to store an Entity that has a creation date. I want to select a single Entity per date. I don't care which one, just one for each creation date. I've been trying sub-select clauses but i can't get them to work. Does anyone have any ideas?

Essentially I have the following Entity:

@Entity
class E {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;

    @Temporal(TemporalType.DATE)
    private Date creationDate;
}

I want to select the following from the table:

ID    DATE
1     3/4/5 <-- SELECT
2     3/4/5
3     4/4/5 <-- SELECT
4     5/4/5 <-- SELECT
5     5/4/5
6     5/4/5

As a work around i'm selecting the dates "SELECT DISTINCT(e.creationDate) ..." and then selecting the entities for each date, but there doesn't seem to be a LIMIT ??? so i'm basically having to select the entire table.

You can override the equals() method of your class E to return true on equals dates. And with this in place, put all your entities fetched from the DB without any constraint into a Set . The set will take care of eliminating duplicates for you based on the date(since your equals method was written in such a way).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM