How to have criteria from multiple entities Hibernate

喜夏-厌秋 提交于 2020-01-25 10:22:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23395216/how-to-have-criteria-from-multiple-entities-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!