如何在 Hibernate 查询语言中查询所有具有关联实体的实体?
How can I query all entities that have an associated entity in Hibernate Query Language?
我很难理解如何查询具有指定类别关联的所有产品。
我可能需要这样的东西
select p.* from product p
inner join product_category pc on p.product_id = pc.product_id
inner join category c on pc.category_id = c.category_id
where c.name = :categoryName;
但在 HQL 中。
假设您使用以下映射:
@Entity
@Table(name = "product")
class Product
{
@Id
@Column(name = "product_id")
private Long id;
@ManyToMany
@JoinTable(name = "product_category",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "product_id")
)
private List<Category> categories;
// getters/ setters
}
@Entity
@Table(name = "category")
class Category
{
@Id
@Column(name = "category_id")
private Long id;
@Column(name = "name")
private String name;
// getters/ setters
}
您可以使用以下 HQL:
select p from Product
join fetch p.categories c
where c.name = :categoryName
我很难理解如何查询具有指定类别关联的所有产品。
我可能需要这样的东西
select p.* from product p
inner join product_category pc on p.product_id = pc.product_id
inner join category c on pc.category_id = c.category_id
where c.name = :categoryName;
但在 HQL 中。
假设您使用以下映射:
@Entity
@Table(name = "product")
class Product
{
@Id
@Column(name = "product_id")
private Long id;
@ManyToMany
@JoinTable(name = "product_category",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "product_id")
)
private List<Category> categories;
// getters/ setters
}
@Entity
@Table(name = "category")
class Category
{
@Id
@Column(name = "category_id")
private Long id;
@Column(name = "name")
private String name;
// getters/ setters
}
您可以使用以下 HQL:
select p from Product
join fetch p.categories c
where c.name = :categoryName