Reputation: 3632
I'm using Neo4j 2.1.7 with SDN 3.3.0.RELEASE in embedded mode.
How can i automatically assign UUIDs to new nodes? What is the best practice when trying to achieve this?
Current Solution:
I added a TransactionEventHandler which automatically add a uuid property to every node. Additionally this handler also blocks the commit when someone tries to remove the uuid.
Problems:
With SDN i always have to reload the entity outside of my transaction in order to use the generated uuid. This limits the usefulness of @Transactional. Is there maybe a way to workaround this?
Upvotes: 0
Views: 204
Reputation: 15086
You have several posibilities
Assign the uuid in entity constructor, the advantage of this is that you can then use the uuid safely in equals and hashCode.
MyNodeEntity() {
uuid = UUID.randomUUID.toString()
....
}
Use lifecycle events, very useful for cases similar to "add uuid if it is not set"
@Bean
ApplicationListener<BeforeSaveEvent> beforeSaveEventApplicationListener() {
return new ApplicationListener<BeforeSaveEvent>() {
@Override
public void onApplicationEvent(BeforeSaveEvent event) {
MyNodeEntity entity = (MyNodeEntity) event.getEntity();
if (!entity.hasUuid()) {
entity.setUuid(UUID.randomUUID.toString());
}
}
};
}
Subclass GraphRepository and override save() method - too complicated for something that can be achieved using the lifecycle events
Upvotes: 1
Reputation: 3632
I just enhanced my save method in my entity service implementation which will set the uuid upfront when it determined that the given entity is new.
Entity:
public boolean isNew() {
return null == getId();
}
EntityServiceImpl:
@Override
public T save(T node) {
if (node.isNew() && node.getUuid() == null) {
node.setUuid(UUIDTransactionEventHandler.getUUID());
}
return nodeRepository.save(node);
}
Upvotes: 0