【问题标题】:Where is `_class` built in Spring Data Couchbase when using 'findBy' methods?使用“findBy”方法时,Spring Data Couchbase 中的“_class”在哪里?
【发布时间】:2017-07-26 23:32:35
【问题描述】:

我可以扩展/覆盖 Spring Data 中的哪些类以使 where 子句包含继承基础实体/模型的类?

详细说明....

以下是一些从“基础”Activity 类扩展而来的模型:

@Document
public abstract class Activity {
}

@Document
public class CommentActivity extends Activity {
}

@Document
public class ShareActivity extends Activity {
}

当保存这些模型时,我使用了一个如下定义的单一存储库类和一个“findBy”方法:

@Repository("activityRepository")
public interface Activity extends CouchbaseRepository<Activity, String>, CouchbaseRepositoryCustom<Activity, String> {

    Page<Activity> findByPersonId(String personId, Pageable pageable);

}

// saving a model in my application would be like so
activityRepository.save(new CommentActivity());

当从 Couchbase 检索这个时,结构返回如下:

{
    "_CAS": 123234342354345,
    "_ID": "0001",
    "_class": "com.myproject.models.CommentActivity",
    "comment": "yo",
    "dateCreated": 1400000000000,
    "dateUpdated": 1400000000000,
    "personId": "0001"    
}

该项目正在使用 Spring Data Couchbase 2.2.0.RELEASE。基于上面的 Repository 接口,调用 findByPersonId 方法会自动生成一个查询,该查询只包含 where 子句中的基类。

WHERE (`personId` = "0001") AND `_class` = "com.myproject.models.Activity" 

就我而言,我想包括从 Activity 扩展的所有类型,如下所示:

   WHERE 
          (`_class` = "com.myproject.models.Activity" 
             OR `_class` = "com.myproject.models.UpdatedActivity" 
             OR `_class` = "com.myproject.models.StatusChangedActivity") 
   AND personId = "0001"

【问题讨论】:

  • 这是 IMO 当前实施的一个缺点。也许提供在 @Document 注释中设置歧视性标准将是一个很好的功能请求? (就像一个额外的字段,在 Couchbase 世界中 type 很常见),用于 WHERE 子句,而 _class 仅用于反序列化。

标签: spring spring-data-jpa spring-data-couchbase


【解决方案1】:

您可以定义自己的查询字符串,例如

@Query("#{#n1ql.selectEntity} WHERE personId = ${'$'}personId AND (_class='com.myproject.models.UpdatedActivity' OR _class='com.myproject.models.StatusChangedActivity'")
fun findByPersonId(@Param("personId") personId: String): List<Activity>

上面的代码是用 Kotlin 编写的,但我猜很容易适应 Java。

请注意,我必须将 @N1qlPrimaryIndexed 添加到存储库类中。

【讨论】:

    猜你喜欢
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多