Hibernate使用条件或hql查询/实现多个表

时间:2017-03-02 18:33:29

标签: java hibernate hibernate-mapping hibernate-criteria

我是Hibernate的新手,想要实现hibernate标准或hql查询多个表来获得结果,我有问题要做到这一点.. 现在我在hibernate中使用本机sql来完成我需要的但是想用hql / criteria尝试相同的.. 下面是我用来获取结果的本机查询..

select table1.dmname,table2.polname,table3.path,table4.uidname 
    from table1,table2,table3,table4
    where table3.dmnid = table1.dmnid
    and table3.polid = table2.polid
    and table3.3.uid = table4.uid

下面是我的实体pojo类

表1:

@Entity
@Table(name = "table1", uniqueConstraints = @UniqueConstraint(columnNames = "dmname"))
        @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="domain")
public class table1  {

    private String dmnid;
    private String dmnname;

    @Id
    @Column(name = "dmnid", unique = true, nullable = false)
    public String getDmnid() {
        return this.dmnid;
    }

    public void setDmnid(String dmnid) {
        this.dmnid = dmnid;
    }

    @Column(name = "dmnname", unique = true, nullable = false)
    public String getDmnname() {
        return this.dmnname;
    }

    public void setDmnname(String dmnname) {
        this.dmnname = dmnname;
    }

表2:

@Entity
@Table(name = "table2", uniqueConstraints = @UniqueConstraint(columnNames = {
        "dmnname", "polname" }))
public class table2 implements java.io.Serializable {

    private String dmnname;
    private String polid;
    private String polname;

    // getters and setter

表3:

@Entity
@Table(name = "table3")
public class table3 implements java.io.Serializable {

    private String dmnname;
    private String polid;
    private String uid;
    private String path;

    // getters and setters

表4:

@Entity
@Table(name = "table4", uniqueConstraints = @UniqueConstraint(columnNames = "uidname"))
public class table4 implements java.io.Serializable {

    private String uid;
    private String uidname;

    // getters and setters

我还没有实现pojo类中的表之间的映射,我很难理解... 所以出来寻求社区的帮助来救我出去.. 感谢您对此进行调查,并且非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我建议你在这里参考Hibernate文档来详细了解关联。 http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#associations

关于你关于HQL的问题,转换你的原生SQL会看起来像这样(除非你需要任何明确的连接条件):

  Query query = session.createQuery('from table1 t1,table2 t2,table3 t3,table4 t4
        where t3.dmnid = t1.dmnid
        and t3.polid = t2.polid
        and t3.uid = t4.uid');
  List results = query.list();