6

I'm new to Neo4J and I have, probably an easy question.

There're NodeEntitys in my application, a property (name) is annotated with @Indexed(unique = true) to achieve the uniqueness like I do in JPA with @Column(unique = true).

My problem is, that when I persist an entity with a name that already exists in my graph, it works fine anyway. But I expected some kind of exception here...?! Here' s an overview over basic my code:

@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);
    }
}

And this is my test:

@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);
}

That's the point where I expect something to go wrong! How can I ensure the uniqueness of a property, without checking it for myself??

P.S.: I'm using neo4j 1.8.M07, spring-data-neo4j 2.1.0.BUILD-SNAPSHOT and Spring 3.1.2.RELEASE.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Markus Lamm
  • 391
  • 1
  • 4
  • 15
  • Please accept answers to your questions. All 3 of your questions are resolved but you haven't accepted any answers! – cod3monk3y Feb 21 '14 at 21:35

2 Answers2

6

I walked into the same trap... as long as you create new entities, you will not see the exception - the last save()-action wins the battle.

Unfortunately, the DataIntegrityViolationException will be raised only in case of update an existing entity!

A detailed description of that behaviour can be found here: http://static.springsource.org/spring-data/data-graph/snapshot-site/reference/html/#d5e1035

Michael K.
  • 497
  • 5
  • 12
5

If you are using SDN 3.2.0+ use the failOnDuplicate attribute:

public class Role extends BaseEntity
{
    @Indexed(unique = true, failOnDuplicate = true)
    private String name;
    ...
}
Lovro Pandžić
  • 5,920
  • 4
  • 43
  • 51