hibernate spring data jpa查询与在postgres db中使用实体管理器调用相同查询相比花费了很长时间?

mbjcgjjk  于 2023-03-03  发布在  Spring
关注(0)|答案(1)|浏览(104)

我正在从postgres DB执行一个简单的选择查询。当我在JPA Repository中使用spring data jpa @Query执行该查询时,查询大约需要6秒。当我使用entityManager.createNativeQuery执行相同的查询时,它需要600毫秒。在我的实体中,也没有到其他实体的Map。我不确定为什么spring data jpa需要那么多时间。

@Entity
@Table(name="transaction_history")
public class TransactionHistory {
    private static final long serialVersionUID = 1L;

    @Id
    private long transactionHistoryId;

    @Column(name = "TRANSACTION_TYPE_ID")
    private int transactionTypeId;

    @Column(name = "SUBSCRIPTION_ID")
    private BigInteger subscriptionId;

    @Column(name = "TRANSACTION_DATE")
    private Date transactionDate;
}

查询耗时6秒:

@Repository
public interface TransactionHistoryRespository extends JpaRepository<TransactionHistory, Long> {
    @Query(value =  "SELECT * FROM (SELECT *"
            + " FROM transaction_history"
            + " WHERE"
            + "      subscription_id = :subscriptionId"
            + "      AND TRANSACTION_TYPE_ID IN (209, 210, 212, 213)"
            + "      AND TOTAL_QUOTE_AMOUNT IS NOT NULL"
            + "      ORDER BY TRANSACTION_DATE DESC) AS transaction_history LIMIT 1"
            , nativeQuery = true)
    TransactionHistory findLastPaymentFailureBySubscriptionId(
            @Param("subscriptionId") BigInteger subscriptionId);

}

查询耗时600毫秒:

javax.persistence.Query query = entityManager.createNativeQuery("SELECT * FROM (SELECT *" +
                "             FROM transaction_history\n" +
                "             WHERE" +
                "            subscription_id = 111901466\n" +
                "            AND TRANSACTION_TYPE_ID IN (209, 210, 212, 213)\n" +
                "            AND TOTAL_QUOTE_AMOUNT IS NOT NULL\n" +
                "            ORDER BY TRANSACTION_DATE DESC) AS transaction_history LIMIT 1");
        List resultList = query.getResultList();

我期待Spring的数据jpa也应该只需要600毫秒。

xxhby3vn

xxhby3vn1#

问题似乎是postgres int8列使用java.math.BigInteger数据类型。更改为java.lang.Long数据类型后,查询时间缩短。
代码之前:

TransactionHistory findBySubscriptionId(
        @Param("subscriptionId") BigInteger subscriptionId);

更新代码:

TransactionHistory findBySubscriptionId(
       @Param("subscriptionId") Long subscriptionId);

此处报告了类似问题:Postgresql table with BigInt primary key column : slow insert

相关问题