通过JPQL

时间:2019-05-14 21:56:35

标签: sql spring jpa jpql

我有以下有效的查询。此查询中的所有表都有某种关系。

@Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {
    @Query("SELECT xref.shortUtlTx FROM CardEntity card " +
            "JOIN card.apexUrlCrossRef xref " +
            "JOIN xref.sampleProdOffer offer " +
            "WHERE xref.apexCard.cardNumber = :cardNum " +
            "AND offer.apexeeOfferId = :myCode"
    )
    List<String> getAllValues(@Param("cardNum") String cardNum, @Param("myCode") String myCode);
} 

但是我也希望将另一个表(实体名称-> UrlCountEntity)连接到该查询,但是该表与该查询中的其他表没有关系。有办法吗?

基于阅读博客的经验,我尝试了以下操作,但会引发错误。 将此行添加到查询中:

  

AND EXISTS(从UrlCountEntity ReferCount中选择SELECT ReferCount在哪里)   ReferCount.url.urlTx = xref.shortUtlTx)

@Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {

    @Query("SELECT xref.shortUtlTx FROM CardEntity card " +
            "JOIN card.apexUrlCrossRef xref " +
            "JOIN xref.sampleProdOffer offer " +
            "WHERE xref.apexCard.cardNumber = :cardNum " +
            "AND offer.apexeeOfferId = :myCode " +
            "AND EXISTS (SELECT referCount FROM UrlCountEntity referCount WHERE referCount.url.urlTx = xref.shortUtlTx)"
    )
    List<String> getAllValues(@Param("cardNum") String cardNum, @Param("myCode") String myCode);

}

错误如下:

  

方法抛出   'org.springframework.dao.InvalidDataAccessResourceUsageException'   

     

无法提取ResultSet; SQL [n / a]

1 个答案:

答案 0 :(得分:1)

基于this article: 使用Hibernate 5.1或更高版本,您可以通过JQPL联接两个不相关的表,就像在SQL中一样:

SELECT first
FROM First first JOIN
    Second second ON first.property = second.property
WHERE first.property = :param

因此,您需要将查询更改为以下内容:

@Query("SELECT xref.shortUtlTx FROM CardEntity card " +
        "JOIN card.apexUrlCrossRef xref " +
        "JOIN xref.sampleProdOffer offer " +
        "JOIN UrlCountEntity referCount ON referCount.url.urlTx = xref.shortUtlTx" +
        "WHERE xref.apexCard.cardNumber = :cardNum " +
        "AND offer.apexeeOfferId = :myCode")
List<String> getAllValues(@Param("cardNum") String cardNum, @Param("myCode") String myCode);