Hibernate HQL查询从与另一个表关联的表中获取数据

时间:2016-04-13 15:05:31

标签: mysql hibernate

我有一个名为Locality的实体: -

@Entity
@Table(name = "CMN_LOCALITY_MASTER")
public class Locality {
    @Id
    @Column(name = "LOCALITY_ID", unique = true, nullable = false,length = 11)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int localityId;

    @Column(name = "LOCALITY_DESCRIPTION",length=70)
    String localityDescription;

    @JsonProperty(access = Access.WRITE_ONLY)
    @ManyToOne
    @JoinColumn(name = "PINCODE_ID")
    Pincode pinCode;

    @JsonIgnore
    @ManyToOne
    City city;
}

包含另一个名为City和Pincode的实体。

城市如下: -

@Entity
@Table(name = "CMN_CITY_MASTER")
public class City{

    @Id
    @Column(name = "CITY_ID", unique = true, nullable = false,length = 11)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int cityId;

    @Column(name = "CITY",length = 150)
    private String description;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "STATE_ID")
    private State state;
}

我想获取具有City ID =(例如1)

的Locality entity / table的所有数据

我尝试了下面的查询: -

@Query("SELECT a FROM Locality a INNER JOIN a.city c WHERE c.cityId=?1")
List<Locality>getAllLocalityByCity(int cityId);

以及

@Query("SELECT a FROM Locality a WHERE a.city.cityId=?1")
List<Locality>getAllLocalityByCity(int cityId);

但这些都不起作用。

您能否建议我查询数据的方式/方式?

此外,是否有Eclipse插件/工具以更快的方式测试HQL查询,而不是为查询中的每个更改重新启动服务器?

您是否也建议您阅读用于学习HQL的文档/书籍?

1 个答案:

答案 0 :(得分:1)

由于您没有提供任何日志或解释,我建议您尝试以下方法:

@Query("SELECT a FROM Locality a INNER JOIN a.city c WHERE c.cityId = :cityId")
List<Locality>getAllLocalityByCity(@Param("cityId") int cityId);

为了学习HQL,我将从Hibernate Docs开始。您也可以查看Criteria API