Phi
Phi

Reputation: 51

Hibernate Criteria multiple tables

currently I'm working with the Hibernate Criteria API and i got following situation:

@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'. Therefore i need the criteria statement.

Can somebody please help me?!

Upvotes: 2

Views: 1308

Answers (1)

Sibi
Sibi

Reputation: 45

I hope you are trying to join two tables using the criteria API.Please Check the below code.

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.

2nd Line - B is joined with the A based on the mapping column

3rd Line - Restriction is made based on Name column in A.

4th Line - Criteria is executed to obtain the list

Also I think there can be mapping of class A in Class B(Many to One).

Upvotes: 1

Related Questions