2012-10-17 74 views
4

我是Neo4J的新手,可能是一个简单的问题。Spring Data Neo4J @Indexed(unique = true)not working

在我的应用程序中有一个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。

+0

请接受解答您的疑问。您的所有问题都已解决,但您尚未接受任何答案! – cod3monk3y

回答

6

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

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

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

+0

感谢迈克尔,经过一番研究后,现在得到了它。 –

+1

这似乎是非常奇怪的行为。 – CorayThan

5

如果您正在使用SDN 3.2.0+使用failOnDuplicate属性:

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

现在有@Indexed注释 - 只是@Index(唯一= true),不能用于开箱即用。 –

相关问题