【问题标题】:Spring Data Neo4J @Indexed(unique = true) not workingSpring Data Neo4J @Indexed(unique = true) 不工作
【发布时间】:2012-10-07 08:28:08
【问题描述】:

我是 Neo4J 的新手,我有,可能是一个简单的问题。

我的应用程序中有 NodeEntitys,属性(名称)使用 @Indexed(unique = true) 进行注释,以实现唯一性,就像我在 JPA 中使用 @Column(unique = true) 所做的那样。

我的问题是,当我坚持一个名称已经存在于我的图表中的实体时,它仍然可以正常工作。 但我预计这里会出现某种异常......?! 这是我的基本代码的概述:

@NodeEntity
public abstract class BaseEntity implements Identifiable
{
    @GraphId
    private Long entityId;
    ...
}

public class Role extends BaseEntity
{
    @Indexed(unique = true)
    private String name;
    ...
}

public interface RoleRepository extends GraphRepository<Role>
{
    Role findByName(String name);
}

@Service
public class RoleServiceImpl extends BaseEntityServiceImpl<Role> implements 
{
    private RoleRepository repository;

    @Override
    @Transactional
    public T save(final T entity) {
    return getRepository().save(entity);
    }
}

这是我的测试:

@Test
public void testNameUniqueIndex() {
    final List<Role> roles = Lists.newLinkedList(service.findAll());
    final String existingName = roles.get(0).getName();
    Role newRole = new Role.Builder(existingName).build();
    newRole = service.save(newRole);
}

这就是我预计会出问题的地方! 如何在不自己检查的情况下确保属性的唯一性??

P.S.:我正在使用 neo4j 1.8.M07、spring-data-neo4j 2.1.0.BUILD-SNAPSHOT 和 Spring 3.1.2.RELEASE。

【问题讨论】:

  • 请接受您的问题的答案。您的所有 3 个问题都已解决,但您尚未接受任何答案!

标签: spring spring-data-neo4j


【解决方案1】:

我走进了同样的陷阱...只要您创建新实体,您就不会看到异常 - 最后一个 save() 操作赢得了战斗。

不幸的是,DataIntegrityViolationException 只有在更新现有实体的情况下才会引发!

可以在此处找到该行为的详细说明: http://static.springsource.org/spring-data/data-graph/snapshot-site/reference/html/#d5e1035

【讨论】:

  • 这看起来真的很奇怪。
【解决方案2】:

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

public class Role extends BaseEntity
{
    @Indexed(unique = true, failOnDuplicate = true)
    private String name;
    ...
}

【讨论】:

  • 现在有了@Indexed 注释——只是@Index(unique = true),不能开箱即用。
猜你喜欢
  • 2014-04-17
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2019-02-06
相关资源
最近更新 更多