Question

I have entities like this:

@Entity
@Table(name = "titul")
public class Titul {
  @OneToMany(mappedBy = "titul") 
  private Set<Autorstvo> autorstvo;

  @Column (name = "nazov")
  private String nazov;
}

@Entity
@Table(name = "autorstvo")
public class Autorstvo {
    @ManyToOne
    @JoinColumn(name="id_autor") 
    private Autor autor;
}

@Entity
@Table(name = "autor")
public class Autor {
    @Column (name = "meno")
    private String meno;

    @OneToMany(mappedBy = "autor")
    private Set<Autorstvo> autorstvo;
}

And i want to have SELECT by criteria Titul.nazov and Autor.meno

So far i did this in Hibernate:

Criteria critT = session.createCriteria(Titul.class);

critT.add(Restrictions.like("nazov", titul));
critT.createAlias("titul.autorstvo", "autorstvo");
critT.createAlias("autorstvo.autor", "autor");
critT.add(Restrictions.ilike("autor.meno", autor));
    critT.list();

But It always ends when trying to execut critT.list()

What am I doing wrong? How can i add JOINed criterias to criteria in Hibernate?

Was it helpful?

Solution

This solved my problem:

Hibernate Criteria Join with 3 Tables

Forgot to add alias to criteria creation also

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explain in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top