如何使用HQL编写sql join查询

时间:2013-11-01 11:11:22

标签: sql hibernate

我有两个实体AddressEntityCompanyEntity

地址实体

@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 个答案:

答案 0 :(得分:1)

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

这将为您提供至少有CompanyEntitiesAddressEntity的列表。

如果添加以下行:

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

您可以通过AddressEntities获得c.list()的列表。

告诉我你是否需要别的东西。