0

我有两个实体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

4

1 回答 1

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

这将为您CompanyEntities提供至少一个AddressEntity.

如果添加以下行:

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

你会AddressEntities通过做得到一个列表c.list()

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

于 2013-11-01T11:45:41.850 回答