Where is `_class` built in Spring Data Couchbase when using 'findBy' methods?

南笙酒味 提交于 2020-07-21 07:38:07

问题


Which classes in Spring Data can I extend/override to have the where-clause include the classes that inherrit the base entity/model?

To elaborate....

Here are a few models that extends from a "base" Activity class:

@Document
public abstract class Activity {
}

@Document
public class CommentActivity extends Activity {
}

@Document
public class ShareActivity extends Activity {
}

When saving these models, I am using a single repository class as define below with a "findBy" method:

@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());

When retrieving this back from Couchbase, the structure is returned like so:

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

The project is using Spring Data Couchbase 2.2.0.RELEASE. Based on the Repository Interface above, calling the findByPersonId method would auto-generate a query that only contains the base class in the where-clause.

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

In my case, I would like to include all types that extends from Activity like so:

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

回答1:


You can define your own query string such as

@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>

The above code is in Kotlin, but I guess easily adaptable to Java.

Please note that I had to add @N1qlPrimaryIndexed to the repository class.



来源:https://stackoverflow.com/questions/42636774/where-is-class-built-in-spring-data-couchbase-when-using-findby-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!