其他分享
首页 > 其他分享> > Spring Data Neo4j – repository.save和@Indexed(unique = true)

Spring Data Neo4j – repository.save和@Indexed(unique = true)

作者:互联网

今天我尝试了Spring Data Neo4j,终于让它以某种方式工作……

我正在使用:

>春季4.0.2
> Spring Data Neo4j 3.0.0
> QueryDSL 3.3.1
> Neo4j 2.0.1

这是我的配置:

@Configuration
@EnableNeo4jRepositories(includeFilters=@Filter(value=GraphRepository.class, type=FilterType.ASSIGNABLE_TYPE))
public class Neo4jConfig extends Neo4jConfiguration {

    public Neo4jConfig() {
        setBasePackage("my.base.package");
    }

    @Bean
    public GraphDatabaseService graphDatabaseService() {
        return new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/neo4j");
    }

}

我的域类:

@NodeEntity
@QueryEntity
public class User implements Persistable<Long> {

    @GraphId private Long id;
    public Long getId() { return id; }

    @NotNull @NotBlank @Email
    @Indexed(unique=true)
    private String email;
    public String getEmail() { return email; }
    void setEmail(String email) { this.email = email; }

    @Override
    public boolean isNew() {
        return id==null;
    }

    @Override
    public int hashCode() {
        return id == null ? System.identityHashCode(this) : id.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

而我的知识库:

interface UserRepository extends GraphRepository<User>, CypherDslRepository<User> {}

我可以在DB中成功创建用户,然后通过以下方式检索它:

User u = repo.query(
    start(allNodes("user"))
        .where(toBooleanExpression(QUser.user.email.eq("my@email.com")))
        .returns(node("user")), new HashMap<String, Object>())
    .singleOrNull();

但是:如果我现在第二次调用我的创建代码,它将不会因为@Indexed(unique = true)字符串电子邮件而抛出异常,它只会覆盖数据库中的对象.

AND:如果我尝试使用不同的电子邮件值创建第二个用户,则会覆盖旧用户.

创建代码就像下面这样简单:

User u = new User();
u.setEmail("some@email-address.com");
repo.save(u);

我还尝试使用独立版本的Neo4j而不是嵌入版本,结果完全相同.在webadmin视图中我可以看到,它创建了一些索引:

Node Indexes:                 Relationship Indexes:

User     {"type":"exact"}     __rel_types__   {"type":"exact"}
lucene                        lucene

调试输出还告诉我Spring创建了一个索引:

2014-03-12 21:00:34,176 DEBUG  o.s.data.neo4j.support.schema.SchemaIndexProvider:  35 - CREATE CONSTRAINT ON (n:`User`) ASSERT n.`email` IS UNIQUE
2014-03-12 21:00:34,177 DEBUG     o.s.data.neo4j.support.query.CypherQueryEngine:  63 - Executing cypher query: CREATE CONSTRAINT ON (n:`User`) ASSERT n.`email` IS UNIQUE params {}

一些更多的调试输出:

curl -v http://localhost:7474/db/data/index/node

{
  "User" : {
    "template" : "http://localhost:7474/db/data/index/node/User/{key}/{value}",
    "provider" : "lucene",
    "type" : "exact"
}


curl -v http://localhost:7474/db/data/schema/index

[ {
  "property_keys" : [ "email" ],
  "label" : "User"
} ]


curl -v http://localhost:7474/db/data/schema/constraint

[ {
  "property_keys" : [ "email" ],
  "label" : "User",
  "type" : "UNIQUENESS"
} ]

我真的无法想象我在这里做错了什么……

请帮我!

更新#1:

从我在AbstractGraphRepository.save中看到的,它使用了Neo4jTemplate.save,它说:

Stores the given entity in the graph, if the entity is already attached to the graph, the node is updated, otherwise a new node is created.

所以我认为它总是“认为”我的实体已经附加了.但为什么?

更新#2:

如果我去webadmin做两次:

CREATE (n:User {email:'test@mail.com'})

我收到一个错误.所以我的Java代码或SDN一定有问题……

更新#3:

Spring Data Neo4j的save方法做了类似GET或CREATE的事情:

User u1 = new User();
u1.setEmail("a@email.com");
repo.save(u1); // creates node with id=0

User u2 = new User();
u2.setEmail("b@email.com");
repo.save(u2); // creates node with id=1

User u3 = new User();
u3.setEmail("a@email.com");
repo.save(u3); // updates and returns node with id=0

我该如何解决这个问题?我想要一个例外.

更新#4:

好像我正在寻找:http://docs.neo4j.org/chunked/stable/rest-api-unique-indexes.html#rest-api-create-a-unique-node-or-return-fail-create

Map<String, Object> prop1 = new HashMap<String, Object>();
prop1.put("email", "abc@mail.com");
neo4jTemplate.createNodeAs(User.class, prop1);

Map<String, Object> prop2 = new HashMap<String, Object>();
prop2.put("email", "abc@mail.com");
neo4jTemplate.createNodeAs(User.class, prop2);

这样它按预期工作,至少我得到一个例外:

org.neo4j.rest.graphdb.RestResultException: Node 7 already exists with label User and property "email"=[abc@mail.com]

但是现在我无法弄清楚如何将它与Spring Data Repository集成…

解决方法:

如果您使用的是SDN 3.2.0,请使用failOnDuplicate属性:

@Indexed(unique = true, failOnDuplicate = true)

标签:spring,spring-data,unique-constraint,neo4j,spring-data-neo4j
来源: https://codeday.me/bug/20190703/1365489.html