JPA QueryBuilder

时间:2011-11-18 13:41:57

标签: java jpa query-builder

请帮忙创建一个查询! 我必须通过common parent对象按categoryId选择所有标签。

我有下一个:

@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>();

...

标记对象:

@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;

....

和Category对象:

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

@Id
@GeneratedValue
private long id;

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

.....

所以我需要按类别ID选择属于特定类别的所有标签。这对我来说有点复杂!

请任何人帮忙!

1 个答案:

答案 0 :(得分:2)

您无需为此使用标准。标准应该用于根据可变搜索条件动态组合查询。

以下是您可以使用的JPQL:

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

如果你有双向关联,那可能会感觉更自然。然后你可以使用

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

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