来自JPA的Spring数据neo4j的@Formula注释的类比?

时间:2016-09-20 21:07:41

标签: cypher spring-data-neo4j spring-data-neo4j-4

我想使用neo4j在数据库级别计算我的域对象的一些属性并返回只读结果。在JPA中,可以通过域对象实体字段上的@Formula注释实现此目的:

@Formula("(select avg(f.rating) from Feedback f where f.offer_id = offer_id)")
private Double rating;

在Spring数据neo4j中应该怎么做才能实现相同的行为?我写了一个Cypher查询,但不知道在哪里使用它。

1 个答案:

答案 0 :(得分:4)

使用@QueryResult

可以实现类似的结果
  • 创建一个包含字段的类以保存返回数据。
  • 使用@QueryResult
  • 对其进行注释

示例: (在Kotlin中,这就是我手边的内容)

@QueryResult
open class Principal constructor(applicationToken: String,
                             profileId: String,
                             stageName: String,
                             showMeLaterDays: Float,
                             roles: Array<Role>)
{

    var applicationToken: String
    var profileId: String
    var stageName: String
    var showMeLaterDays: Float

    @Convert(RoleArrayAttributeConverter::class)
    var roles: Array<Role>



    init
    {
        this.applicationToken = applicationToken
        this.profileId = profileId
        this.stageName = stageName
        this.showMeLaterDays = showMeLaterDays
        this.roles = roles
    }

    //Provide a default constructor for OGM
    constructor() : this(applicationToken = "", profileId = "", stageName = "", showMeLaterDays = 0f,
        roles = emptyArray())
}

然后将其与存储库一起使用,如下所示:

@Query("MATCH (n:CandidateProfile {applicationToken: {0} }) 
    RETURN n.id as profileId, n.applicationToken as applicationToken, n.stageName as stageName, n.showMeLaterDays as showMeLaterDays, n.roles as roles;")
fun findByApplicationToken(token: String): Principal?
  • 请注意返回节点属性以与类字段名称对应的方式。
  • 功能结果也可以这样做。