Spring Data Neo4j:特定顺序的关系

时间:2015-08-28 12:29:19

标签: spring neo4j spring-data spring-data-neo4j

我正在使用Spring Data Neo4j,我有两个实体,PersonPhoneNumberPersonPhoneNumber有1-N的关系。我正在寻找一种方法来始终按照特定的顺序建立这种关系。

这是我的实体的定义(那些是Groovy类):

@NodeEntity
class Person {
    @GraphId Long id
    String name
    @RelatedToVia
    Set<NumberRel> numbers
}

@RelationshipEntity(type = "has_number")
class NumberRel {
    @GraphId Long id
    @StartNode Person person
    @EndNode PhoneNumber number
    int sequence
}

@NodeEntity
class PhoneNumber {
    @GraphId Long id
    String number
}

interface PhoneNumberRepository extends GraphRepository<PhoneNumber>, CypherDslRepository<PhoneNumber> {
    /* Empty */
}

interface PersonRepository extends GraphRepository<Person>, CypherDslRepository<Person> {
    Person findByName(String name)
}

然后我创建并保存一些实体:

def num01 = new PhoneNumber(number: "0101")
phoneNumberRepository.save(num01)
def num02 = new PhoneNumber(number: "0202")
phoneNumberRepository.save(num02)

def alice = new Person(
    name: "Alice", 
    numbers: new LinkedHashSet<NumberRel>()
)
alice.numbers << new NumberRel(
    person: alice,
    sequence: 10,
    number: num01
)
alice.numbers << new NumberRel(
    person: alice,
    sequence: 20,
    number: num02
);
personRepository.save(alice)

这就是我被困住的地方:我想告诉Spring - 或Neo4j - 加载按sequence属性的值排序的NumberRel关系。我找不到办法做到这一点。

现在,订单是随机的。以下代码证明了这一点:

(1..3).each {
    println "Looking for Alice, pass ${it}"
    def p = personRepository.findByName("Alice")
    p.numbers.each { number ->
        print "${number.sequence} "
    }
    println()
}
产生此输出的

Looking for Alice, pass 1
10 20 
Looking for Alice, pass 2
20 10 
Looking for Alice, pass 3
10 20 

所以我的问题是:是否可以通过NumberRel.sequence对Person.numbers进行排序?

1 个答案:

答案 0 :(得分:0)

如果SDN无法对结果进行排序,请先将集合发送到排序 -

(1..3).each {
    println "Looking for Alice, pass ${it}"
    def p = personRepository.findByName("Alice")
    p.numbers.sort{it.sequence}
    p.numbers.each { number ->
        print "${number.sequence} "
    }
    println()
}