如何将此原始查询转换为Jpa查询?

时间:2017-01-20 17:33:07

标签: java sql hibernate spring-data-jpa jpql

我有以下原始查询:

SELECT CD.* FROM COUNTRY_DETAIL CD, COUNTRY CT where CD.COUNTRY_CODE = CT.COUNTRY_CODE AND CD.LANGUAGE_CODE = 'EN' AND CT.CITIZENSHIP_IND='Y' 

在我的Java项目中,实体CountryDetail对应COUNTRY_DETAIL表,Country实体对应COUNTRY表。它们如下:

CountryDetail.java:

@Entity
public class CountryDetail implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "COUNTRY_DETAIL_ID")
    private long id; /* id public getter and setter exist */

    @Column(nullable = false, length = 2)
    private String languageCode; /* languageCode public getter and setter exist */

    @ManyToOne
    @JoinColumn(name = "COUNTRY_CODE", referencedColumnName = "COUNTRY_CODE")
    private Country country; /* country public getter and setter exist */


    public String getCountryCode(){
        return this.iCountry.getCountryCode();
    }

}

Country.Java:

@Entity
public class Country implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "COUNTRY_ID")
    private long id; /* id public getter and setter exist */

    @Column(name="COUNTRY_CODE", nullable = false, unique = true, length = 2)
    private String countryCode; /* countryCode public getter and setter exist */

    @Column(nullable = false, length = 60)
    private String officialName; /* officialName public getter and setter exist */

    @Column(nullable = true, length = 1)
    private String citizenshipInd; /* citizenshipInd public getter and setter exist */


    @OneToMany(mappedBy="country")
    private List<CountryDetail> countryDetails = new ArrayList<CountryDetail>();
    public List<CountryDetail> getCountryDetails() {
        return countryDetails;
    }

}

如何将原始查询转换为Jpa查询?我的尝试如下(输入已经参数化,而不是像原始查询中那样硬编码):

@Query("SELECT distinct cd FROM CountryDetail cd, Country ct WHERE UPPER(cd.languageCode) = TRIM(UPPER(:langcode)) and UPPER(cd.country.citizenshipInd) = TRIM(UPPER(:citizenshipindicator))")

这给了我预期的结果(CountryDetail的列表),但是只有在我添加distinct之后,返回包含多次重复的预期结果。是否有可能在没有独特查询的情况下获得结果,或者由于JPA处理相互依赖的实体的方式而无法避免这种结果?

谢谢。

0 个答案:

没有答案