Specify the UUID of a JCR node in code
This article shows how to set the UUID of a JCR node in code to maintain consistency across systems. Magnolia CMS provides several convenience classes and methods for working with the underlying JCR repository, such as the
info.magnolia.jcr.util.NodeUtil
class that provides methods for creating or updating content nodes - but none of these provide a way to set the UUID property directly.
If you have a technical background working with Magnolia CMS or any other JCR content system, you know about the ability to keep IDs the same when using import/export functionality.
If you dig around in Jackrabbit core classes like org.apache.jackrabbit.core.NodeImpl, you will indeed find the method
public Node addNodeWithUuid (String relPath, String nodeTypeName, String uuid) throws RepositoryException {
return perform(new AddNodeOperation(this, relPath, nodeTypeName, uuid));
}
which solves the problem of setting a JCR UUID in code, see also Preserving UUID and document version history on repository migration.
Setting the UUID in Magnolia code
Typically, in Magnolia CMS, you will be working with nodes that are of type javax.jcr.Node, which has no direct way to “manually” set the UUID. As we saw above, the NodeImpl class has the required method, so what we can do is cast the existing java.jcr.node to the NodeImpl incarnation. We accomplish this by unwrapping the node.
Example pseudocode
// info.magnolia.jcr.util.NodeUtil
// java.jcr.Node myParentNode
final Node myUnwrappedNode = NodeUtil.unwrap(myParentNode);
((NodeImpl) myUnwrappedNode).addNodeWithUuid("my/node/path", "mgnl:page", "d172344e-6164-4268-8782-d03766b0e82e")
Of course, you would create a generic method and not use static values.