0

Please help to create a query! I have to select all Tags by categoryId via common parent object.

I have next:

@Table(name="ADVERT")
@Entity(name="Advert")
public class JpaAdvert implements Advert{

@Id
@GeneratedValue
private long id;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="category_id", referencedColumnName="id")
private JpaCategory category = new JpaCategory();

@ManyToMany(fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name="ADVERT_TAGS", joinColumns=@JoinColumn(name="advert_id",referencedColumnName="id"), inverseJoinColumns=@JoinColumn(name="tag_id", referencedColumnName="id"))
private Set<JpaTag> tags = new HashSet<JpaTag>();

...

The tag object:

@Entity(name="Tag")
@Table(name="TAG")
public class JpaTag implements Tag {

@Id
@GeneratedValue
private long id;

private String name;

private long weight=1;

private String locale;

....

and the Category object:

@Table(name="CATEGORY")
@Entity(name="Category")
public class JpaCategory implements Category {

@Id
@GeneratedValue
private long id;

@Column(name="category_name")
private String categoryName;

.....

So I need to select ALL tags which belong to specific category by category ID. It's a bit complicated for me how to do it!

Help please anybody!

Gray
  • 115,027
  • 24
  • 293
  • 354

1 Answers1

2

You don't need to use criteria for this. Criteria should be used to dynamically compose a query based on variable search criteria.

Here's the JPQL you could use:

select distinct tag from Advert a
inner join a.tags tag
where a.category.id = :categoryId

It would probably feel more natural if you had bidirectional associations. You could then use

select tag from Tag tag where tag.advert.category.id = :categoryId

or

select tag from Tag tag
inner join tag.advert a
where a.category.id = :categoryId
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255