Saturday, 17 May 2025

DSLQuery (or Dynamic Query) in Liferay DXP

DSLQuery (or Dynamic Query) in Liferay DXP

In Liferay DXP 7.3 and later, DSLQuery provides a modern, type-safe API to query your database. It replaces the older DynamicQuery mechanism and integrates deeply with Service Builder entities.

🛠 Prerequisites

  • Liferay DXP 7.3 or higher
  • Service Builder module with generated entities
  • Familiarity with Java and Liferay’s modular structure

🔎 What is DSLQuery?

DSLQuery (Domain Specific Language Query) is a fluent API built on top of SQL. It’s used to perform select, count, and aggregate operations on Service Builder entities.

🔁 Example: Fetch All Products Using DSLQuery

import com.example.sb.model.ProductTable;
import com.example.sb.model.Product;
import com.liferay.petra.sql.dsl.query.DSLQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.service.persistence.impl.BasePersistenceImpl;

import java.util.List;

DSLQuery dslQuery = DSLQueryFactoryUtil.select(
    ProductTable.INSTANCE
).from(
    ProductTable.INSTANCE
);

List<Product> products = ProductLocalServiceUtil.dslQuery(dslQuery);
  

🔍 Filtering with WHERE Clause

DSLQuery dslQuery = DSLQueryFactoryUtil.select(
    ProductTable.INSTANCE
).from(
    ProductTable.INSTANCE
).where(
    ProductTable.INSTANCE.price.gt(100.0)
);
List<Product> expensiveProducts = ProductLocalServiceUtil.dslQuery(dslQuery);
  

📊 Aggregate Count with DSLQuery

long count = ProductLocalServiceUtil.dslQueryCount(
    DSLQueryFactoryUtil.count(
        ProductTable.INSTANCE.productId
    ).from(ProductTable.INSTANCE)
);
  

🕵️ DynamicQuery (Older Approach)

Still supported in Liferay 7.x, useful for backwards compatibility:

DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(Product.class);
dynamicQuery.add(RestrictionsFactoryUtil.gt("price", 100.0));
List<Product> results = ProductLocalServiceUtil.dynamicQuery(dynamicQuery);
  

📘 When to Use DSLQuery vs DynamicQuery

  • Use DSLQuery – For new development, better performance, type safety
  • Use DynamicQuery – When maintaining older codebases, or where DSLQuery support is missing

⚠️ Notes

  • DSLQuery returns raw models (not wrapped with SOAP or JSON layers).
  • Make sure to import correct classes (especially ProductTable) from generated API module.
  • DSLQuery does not support all SQL features (e.g., joins between unrelated tables may be limited).

📚 Resources

✅ Conclusion

DSLQuery is Liferay’s preferred querying mechanism for efficient and type-safe data access in OSGi-based modular projects. You should prefer it over DynamicQuery for new development.

No comments:

Post a Comment