[英]Java/JPA Select unique entities
I'm using JPA to store an Entity that has a creation date. 我正在使用JPA存储具有创建日期的实体。 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 ??? 作为一种变通方法,我选择日期“ SELECT DISTINCT(e.creationDate)...”,然后为每个日期选择实体,但似乎没有限制? 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. 您可以重写类E
的equals()
方法,以在相等日期返回true。 And with this in place, put all your entities fetched from the DB without any constraint into a Set
. 并将其放置在适当的位置,将不受任何约束地从数据库中获取的所有实体放入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). 该集合将根据日期为您消除重复项(因为equals方法是以这种方式编写的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.