Working with JCR in Magnolia-CMS

Magnolia CMS is popular Java-based CMS, but unfortunately there is not enough documentation regarding it. For example, I decide to store and load some data into built-in JCR repository and I did not find guide for it. Thus I decided to create this post.

So my goal is use JCR as storage for my custom data. I want to store data into it and load data.

So let’s start. First I’d to get Content and then add same entities into it.

info.magnolia.cms.util.ContentUtil is main class, which we will use. Its getContent-method returns content by id of repository and path to content. The following screen illustrates where you may find name of repositories (by the way name of repository equals to id of repository 🙂 ) and how to use path.

So the following code check does “myfolder” (I will use this folder for storing my entities) exist and creates it if it doesn’t exist:

Content myfolder = ContentUtil.getContent(“website”, “/myfolder”);
if (myfolder == null) {
final Content root = ContentUtil.getContent(“website”, “/”);
myfolder = root.createContent(“myfolder”);;

Note that I call save-method of owner of created content – not of this content.

After that we have created myfolder and now we may start to add entities into it by the following way:

final Content contentNode = myfolder.createContent(entityname, ItemType.CONTENTNODE);;

contentNode.createNodeData(“property1”, PropertyType.LONG).setValue(each.getId());
contentNode.createNodeData(“property2”, PropertyType.STRING).setValue(each.getText());
contentNode.createNodeData(“property3”, PropertyType.DATE).setValue(Calendar.getInstance());;

So here entityname is name of entity, which should be created and contentNode is representation of it and you should call save-method of parent folder for creating this entity. After that you may specify properties of this entity by creating node data and setting values of it. When all properties are specified you may store all changes by calling save-method of contentNode.

In conclusion, I’d note that all ContentUtil uses Context, which is stored and managed by MgnlContext. By default it has right of current user.