如果该表中不存在某列,如何跳过查询方法中的列

问题描述 投票:0回答:1

假设我们有这样的查询:

    @Query(value = "SELECT T.id FROM TrackingResultEntity T WHERE T.creationDate < :purgeBefore AND T.transactional = :transactional AND T.type = :type")

这是在一个被子存储库覆盖的父存储库中,假设由于某种原因我无法将“类型”列用于特定的子存储库,因为它不存在,我该怎么做?

谢谢

java sql spring-boot spring-data-jpa
1个回答
0
投票
Solution 1: 
In the parent repository, make type optional by setting it to null if it’s not used.
Add a condition to include type in the WHERE clause only if it’s provided.

@Query(value = "SELECT T.id FROM TrackingResultEntity T WHERE T.creationDate < :purgeBefore AND T.transactional = :transactional" +
               " AND (:type IS NULL OR T.type = :type)")
List<Long> findTrackingResults(@Param("purgeBefore") Date purgeBefore,
                               @Param("transactional") boolean transactional,
                               @Param("type") String type);
In this approach:

If the type parameter is null (e.g., not set by the child repository), the WHERE clause ignores type, effectively not filtering by it.
If type is provided, it filters by type as usual.


Solution 2: Override the Query in the Child Repository

In the parent repository, define the query as usual.
In the child repository, override the method without the type parameter.

In Parent Repository:

@Query(value = "SELECT T.id FROM TrackingResultEntity T WHERE T.creationDate < :purgeBefore AND T.transactional = :transactional AND T.type = :type")
List<Long> findTrackingResults(@Param("purgeBefore") Date purgeBefore,
                               @Param("transactional") boolean transactional,
                               @Param("type") String type);
In Child Repository (without type):

@Query(value = "SELECT T.id FROM TrackingResultEntity T WHERE T.creationDate < :purgeBefore AND T.transactional = :transactional")
List<Long> findTrackingResults(@Param("purgeBefore") Date purgeBefore,
                               @Param("transactional") boolean transactional);
With this approach:

The child repository completely overrides the query, bypassing the need for the type column entirely.

https://admirable-smakager-729141.netlify.app/post/4
© www.soinside.com 2019 - 2024. All rights reserved.