如何在Hibernate One to Many关系中获取记录

时间:2017-01-27 13:23:41

标签: java hibernate one-to-many

我有2个POJO类:Ownerdetials(父表) 和Vehiclemaster(儿童表)。 我想获得属于oname表的所有Vehicle(表示所有者名称)。

我的课程:

Ownerdetails.java:

public class Ownerdetails  implements java.io.Serializable {
    private Integer ownerid;
    private String oname;
    private String panno;
    private String mobile;
    private String address;
    private String pincode;
    private String city;
    private String state;
    private String country;
    private String accno;
    private String bankname;
    private String branch;
    private String ifccode;
    private Set vehiclemasters = new HashSet(0);
    //Setter and Getter method 
 }

Vehiclemaster.java:

public class Vehiclemaster  implements java.io.Serializable {
    private Integer vid;
    private Ownerdetails ownerdetails;
    private String vno;
    private String vname;
    private String driverlicense;
    private String unladenWeight;
    private String drivername;
    private String vtype;
    private String inscompname;
    private String instype;
    private String insfrom;
    private String insto;
    private String fitnessdatefrom;
    private String fitnessdateto;
    //Setter and Getter Method
}

下面是我的SQL查询,如何在Hibernate HQL Query中进行转换?

select ownerdetails.oname from ownerdetails,vehiclemaster 
WHERE ownerdetails.ownerid=vehiclemaster.ownerid; 

我用Google搜索,但没有得到正确的结果。

1 个答案:

答案 0 :(得分:0)

<强>映射

public class Ownerdetails  implements java.io.Serializable {

  @Id
  private Integer ownerid;

  @OneToMany(mappedBy = "ownerdetails")
  private Set<Vehiclemaster> vehiclemasters = new HashSet(0);

}

public class Vehiclemaster  implements java.io.Serializable {

   @Id
   private Integer vid;

   @ManyToOne 
   @JoinColumn(name = "ownerid")
   private Ownerdetails ownerdetails;

}

<强>查询

select distinct od.oname 
from Ownerdetails od
   inner join od.vehiclemasters vm
where vm.vname = 'name'  // optional