Reputation: 593
I have two entities: Event and Comment.
@Entity
@Table(name = "events")
public class Event extends BaseEntity {
@Id
@Column(name = "event_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long eventId;
@Column(name = "title", length = 200)
protected String title;
@OneToMany(mappedBy = "event", cascade = CascadeType.REMOVE)
@LazyCollection(LazyCollectionOption.FALSE)
protected List<Comment> comments;
}
@Entity
@Table(name = "comments")
public class Comment extends BaseEntity {
@Id
@Column(name = "comment_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long commentId;
@ManyToOne(optional = false)
@JoinColumn(name = "event_id", referencedColumnName="event_id", nullable = false)
protected Event event;
@Column(name = "update_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
protected Date updatedTimestamp;
}
So each event has a list of comments and each comment has an update time.
I want to use Criteria API to construct a query such that choose all events that has at least one new comments. (New comment means its update time is later than a given date time)
Thanks for anyone helping me.
Sorry the question I asked above is not complete: what I want is use Criteria API to construct a query such that choose all events that has at least one new comments and eventId is equal to some specific eventId.
I have tried: (Given Date lastCheckedTime
and Long eventId
)
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Event> cq = cb.createQuery(Event.class);
Root<Comment> c = cq.from(Comment.class);
Predicate lastCheckedTimeCondition = cb.greaterThanOrEqualTo(
c.get(Comment_.updatedTimestamp), lastCheckedTime);
cq.where(lastCheckedTimeCondition);
cq.select(c.get(Comment_.event));
TypedQuery<Event> query = em.createQuery(cq);
result = query.getResultList();
the above code can choose events that have new comments but now I don't know how to add the conditon about the eventId.
Upvotes: 0
Views: 559
Reputation: 692131
Create a join on the event, and apply the restriction on the ID of the event:
Join<Comment, Event> event = c.join(Comment_.event);
Predicate eventIdPredicate = cb.eq(event.get(Event_.eventId), theEventId);
And then use CriteriaBuilder's and method to combine the two predicates into one as shown by Lukas's answer.
Upvotes: 1
Reputation: 221220
CriteriaBuilder
has an and(Predicate...) method. You would then connect your two predicates:
cq.where(cb.and(lastCheckedTimeCondition, someEventIdCondition));
Upvotes: 1