CRS
CRS

Reputation: 471

JPQL join 2 tables: Writing jpql

I have 2 tables First table - Event Second table - Category

@Entity
public class Event {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long eventId;
private String name;
@ManyToOne
@JoinColumn(name = "category_id")
private EventCategory category;
//getters and setters
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "CATEGORY" }))
public class EventCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long categoryId;
@NotNull
private String category;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private List<Event> events;
}

Now I want all the events whose category is some value. I am very new to jpa. Having hard time writing query for this. It will be help if you can help me out.

Edit: I am storing categoryId in events table. I want to be able to be search by category name. category name is saved only in category table. So I think I need to do a join with category table.

Upvotes: 1

Views: 892

Answers (1)

Perception
Perception

Reputation: 80633

With a query like this:

final String query = "SELECT e FROM Event e WHERE e.category = :category";

You can retrieve records with any of a number of means, but here is one:

final EventCategory category = ...;
TypedQuery<Event> query = entityManager.createQuery(query, Event.class);
query.setParameter("category", category);
final List<Event> events = query.getResultList();

* EDIT *

By default, the method I illustrated above will search based on the primary key defined for your category object. If you want to search by some other property then you need to specify that in your JPQL:

final String query = "SELECT e FROM Event e WHERE e.category.name = :categoryName";

final String categoryName = ...;
TypedQuery<Event> query = entityManager.createQuery(query, Event.class);
query.setParameter("categoryName", categoryName);
final List<Event> events = query.getResultList();

Upvotes: 5

Related Questions