I have two entities one is Event and another is User. User can like events, so it has a list of liked events (which is recorded in a joint table). I want to build a typesafe queries using JPA 2.0 to count how many people like an event given the event id. Could anyone help me with it? Thank you.
Below is the codes for the entities.
@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;
//getter and setter....
}
@Entity
@Table(name = "user")
public class User{
@Id
@Column(name = "login", length = 64)
protected String login;
@OneToMany(cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "user_events",
joinColumns = {@JoinColumn(name = "login")},
inverseJoinColumns = {@JoinColumn(name = "event_id")})
protected List<Event> events;
//getter and setters...
}
Since your query is basically going to be static with the parameter being the event id, I would create a @NamedQuery, then use the entity manager to create a TypedQuery. Since you are looking for the count, the type will likely be a Long.
The query could be something like
select count(u) from User u where :event member of u.eventsassuming you have the event, not just the id.If you have something against NamedQuery you could use the Criteria API to do the same, but where this query is so static I don’t see much point in doing that.