简体   繁体   English

Hibernate Criteria 多表

[英]Hibernate Criteria multiple tables

currently I'm working with the Hibernate Criteria API and i got following situation:目前我正在使用 Hibernate Criteria API,我遇到了以下情况:

@Entity(name = "A")
private class A {
    @Id
    @GenericGenerator(name = "fileEntryIdGenerator", strategy = "increment")
    @GeneratedValue(generator = "fileEntryIdGenerator") 
    @Column(name = "DBID")
    private Long id;

    @Column
    private String name;
    @OneToMany(targetEntity = B.class, cascade = {CascadeType.ALL }, fetch = FetchType.LAZY)   @JoinColumn(name = "A_id")
    private Set<B> references;
    // ....
}

@Entity(name = "B") private class B{
@Id
@GenericGenerator(name = "fileEntryIdGenerator", strategy = "increment")
@GeneratedValue(generator = "fileEntryIdGenerator")
@Column(name = "DBID")
private Long id;   @Column   private String name;...}

Now, my plan is to get a List of all B's where A.name = 'testName'.现在,我的计划是获取所有 B 的列表,其中 A.name = 'testName'。 Therefore i need the criteria statement.因此我需要标准声明。

Can somebody please help me?!有人能帮帮我吗?!

I hope you are trying to join two tables using the criteria API.Please Check the below code.我希望您正在尝试使用标准 API 连接两个表。请检查以下代码。

Criteria criteria = session.createCriteria(B.class, "B");
criteria.createAlias("B.A", "A", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("A.name", "name"));
criteria.list();

In the above code,在上面的代码中,

1st Line - Criteria object is created for the class B.第一行 - 为 B 类创建 Criteria 对象。

2nd Line - B is joined with the A based on the mapping column第二行 - B 根据映射列与 A 连接

3rd Line - Restriction is made based on Name column in A.第 3 行 - 基于 A 中的名称列进行限制。

4th Line - Criteria is executed to obtain the list第 4 行 - 执行 Criteria 以获取列表

Also I think there can be mapping of class A in Class B(Many to One).另外我认为可以在 B 类(多对一)中映射 A 类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM