指定连接条件" ON列"在hibernate HQL中?

时间:2016-07-14 20:41:13

标签: java hibernate

我正在学习Hibernate,我对基本的HQL连接语法有疑问。我正在关注这个tutorial。假设我有一个产品和类别实体,

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

    private long id;
    private String name;

    private Set<Product> products;

    public Category() {
    }

    public Category(String name) {
        this.name = name;
    }

    @Id
    @Column(name = "CATEGORY_ID")
    @GeneratedValue
    public long getId() {
        return id;
    }


    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
    public Set<Product> getProducts() {
        return products;
    }

    // other getters and setters
}
@Entity
@Table(name = "PRODUCT")
public class Product {
    private long id;
    private String name;
    private String description;
    private float price;

    private Category category;

    public Product() {
    }

    public Product(String name, String description, float price,
            Category category) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.category = category;
    }

    @Id
    @Column(name = "PRODUCT_ID")
    @GeneratedValue
    public long getId() {
        return id;
    }

    @ManyToOne
    @JoinColumn(name = "CATEGORY_ID")
    public Category getCategory() {
        return category;
    }

    // other getters and setters
}

所以我必须加入category和Product,我会在sql中使用这样的东西

select * from Category A inner join Product B on A.id=B.category_id,

在HQL中,我们似乎放弃了&#34; on&#34;条件,上述查询的HQL是

String hql = "from Product p inner join p.category";

Query query = session.createQuery(hql);

为什么在HQL中不需要?

1 个答案:

答案 0 :(得分:3)

如果您有关联(例如@ManyToOne),则不需要on,Hibernate会将其添加到SQL中。

这是一个问题,如果你没有关联,那么在Hibernate 5.1之前。从Hibernate 5.1,您可以使用ad hoc连接:

Join unrelated entities in JPA

除此之外,HQL还定义了一个with子句来限定连接条件:

The Hibernate WITH clause, the HQL equivalent of SQL's ON