【问题标题】:Using @MappedSuperclass in spring repository @Query在Spring存储库@Query中使用@MappedSuperclass
【发布时间】:2022-01-12 12:45:04
【问题描述】:

我正在尝试为扩展我的基础存储库的所有存储库定义通用查询:

@NoRepositoryBean
public interface DocumentRepository<T extends BaseDocument> extends JpaRepository<T, Long> {

    @Query(value = "FROM BaseDocument bd WHERE (bd.createdAt IS NULL OR :to IS NULL OR bd.createdAt < :to) AND (bd.deletedAt IS NULL OR :from IS NULL OR bd.deletedAt > :from)")
    Iterable<T> findAllActiveBetween(OffsetDateTime from, OffsetDateTime to);
}

@MappedSuperclass
@Where(clause="deleted_at IS NULL")
abstract public class BaseDocument {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private OffsetDateTime createdAt;

    private OffsetDateTime deletedAt;
}

有问题的部分是在 @Query 中使用 BaseDocument。 是否可以在所有子存储库中定义这样的方法而不重复?

【问题讨论】:

    标签: spring-data-jpa spring-data


    【解决方案1】:

    当您使用@MappedSuperclass 时,继承的类不共享一个可供选择的表,因此它们中的每一个都需要单独的查询。存储库的继承在这里无法帮助您。

    如果您使用其他继承策略,例如joined multiple table inheritance,则可以从超类的表中进行选择,然后您可以使用 java 对象进行导航。如果您需要在查询中使用子类的属性,当然每个子类都需要实现自己的查询。

    @NoRepositoryBean
    public interface DocumentRepository<T extends BaseDocument> extends JpaRepository<T, Long> {
    
        @Query(value = "FROM BaseDocument bd WHERE (bd.createdAt IS NULL OR :to IS NULL OR bd.createdAt < :to) AND (bd.deletedAt IS NULL OR :from IS NULL OR bd.deletedAt > :from)")
        Iterable<T> findAllActiveBetween(OffsetDateTime from, OffsetDateTime to);
    }
    
    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    @DiscriminatorColumn(name="BaseDocument_TYPE")
    @Table(name="BaseDocument")
    abstract public class BaseDocument {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        private OffsetDateTime createdAt;
    
        private OffsetDateTime deletedAt;
    }
    
    @Entity
    @DiscriminatorValue("TextDocument")
    @Table(name="TextDocument")
    public class TextDocument extends BaseDocument {
      private String text;
    }
    
    @Entity
    @DiscriminatorValue("AudioDocument")
    @Table(name="AudioDocument")
    public class AudioDocument extends BaseDocument {
      private byte [] audio;
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2023-03-31
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多