Sling API vs JCR API


Hello Everyone,

AEM is a Web Application Developer based on content. Technology stack of AEM contains both Sling and JCR.
  • What is Sling and JCR 
  • When and how to use sling api and jcr api
What is Sling and JCR 

Sling: AEM is built using sling, a web application framework based on REST principles. Sling uses a JCR repository, such as Apache Jackrabbit, or in the case of AEM, the CRX Content Repository, as its data store. It deploy the application in the form of OSGi bundle.

JCR (Java Content repository) : Basically a place where the content/data is stored. You can store data as nodes and node properties i.e content repository is hierarchical and represented as a tree structure.

When to use sling or JCR

Sling : In the most cases it is recommended to use the sling api. The higher-level API(Sling) is faster to write and far more readable and maintainable in the long run. Even if performance is really needed if we compare both the API the difference will be few milliseconds over the operation on set of nodes.
JCR : JCR is required when performance is strictly needs to be taken. 

If you want to see the performance of both api in details Maciej Matuszewski explained it very deeply in below post.

How to use sling api and jcr api

Assume we need to read page title
code using jcr Api:

Node page = session.getNode("/content/samplepage");
Node jcrcontent = page.getChild("jcr:content");
Property titleProp= jcrcontent.getProperty ("title"):
String title = titleProp.getValue().getString();

code using sling Api: 

Resource resource = resolver.getResource("/content/samplepage");
Page page = resource.adaptTo(Page.class);
String title = page.getTitle();

If you see both code using both api in sling we don't need to know about the node jcr:content. Also title will get directly using getTitle() method, the same in jcr we first need to get property and then value of the property in required form.

adaptTo Method in slingThe adaptTo() method found in many sling objects allows to "transform" objects. 

below are some example of adaptTo() method:
  1. PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
  2. Node node = resource.adaptTo(Node.class);
  3. UserManager userManager=resource.adaptTo(UserManager.class);
  4. User user=resource.adaptTo(User.class);
We can transform custom objects too.

So as per results or consequences we can go for sling for easy readability and maintainability, instead of jcr if performance is not strictly required, as there not much difference in performance.

KEEP EDUCATING YOURSELF!!!!

Comments

Post a Comment

Popular posts from this blog

AEM in docker

Creating AEM project using Maven Archetype