2013-11-01 62 views
0

我有兩個實體AddressEntityCompanyEntity連接查詢。如何寫SQL使用HQL

地址實體

@Entity 
@Table(name = "address") 
public class AddressEntity implements Serializable { 

    private static final long serialVersionUID = 6149442393833549397L; 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private Integer id; 

    @Column(name = "city", nullable = false) 
    private String city; 

    @Column(name = "post") 
    private String post; 

    @Column(name = "street", nullable = false) 
    private String street; 

    @Column(name = "building_nr", nullable = false) 
    private Integer buildingNr; 

    @Column(name = "flat_nr") 
    private Integer flatNr; 

    // setters and getters 
} 

公司實體

@Entity 
@Table(name = "company") 
public class CompanyEntity implements Serializable { 

    private static final long serialVersionUID = 3635072833730133590L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "id") 
    private Integer id; 

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

    @OneToOne 
    @Cascade(CascadeType.ALL) 
    private AddressEntity address = new AddressEntity(); 

    @OneToMany(mappedBy = "company") 
    @Cascade(CascadeType.ALL) 
    private Set<DescriptionEntity> descriptions = new HashSet<DescriptionEntity>(); 

    @OneToMany(mappedBy = "company") 
    @Cascade(CascadeType.ALL) 
    private List<EmployeeEntity> employees = new ArrayList<EmployeeEntity>(); 

} 

我想select all addresses which are used by companies想在這個SQL查詢SELECT a.city, c.name FROM address a INNER JOIN company c ON c.address_id=a.id;但使用HQL查詢(我想使用JOIN,而不是WHERE)。我該怎麼做?我想選擇地址表,而不是公司表的地址。我知道我可以使用公司的表像這樣select c.address.city, c.name from CompanyEntity c或使用WHERE select a.city, c.name from CompanyEntity c, AddressEntity a WHERE c.address.id=a.id選擇地址。

+1

如果你想選擇使用u需要在地址實體@pepuch你爲什麼不寫標準 – wxyz

+0

ADRESS和公司之間的關係添加地址表的公司使用的地址? – RAS

+0

我在休眠全新的。你能寫出你的想法如何解決這個問題嗎? – pepuch

回答

1
Criteria c = session.createCriteria(CompanyEntity.class); 
c.createAlias("address", "address"); 
List<CompanyEntity> companies = c.list(); 

這會給你帶有至少一個AddressEntityCompanyEntities名單。

如果添加以下行:

c.criteria.setProjection(Projections.property("address")); 

你會做c.list()得到AddressEntities列表。

告訴我,如果你需要別的東西。