Quantcast
Channel: It's all about Java and Liferay
Viewing all articles
Browse latest Browse all 12

Dynamic Query in Liferay

$
0
0
Liferay provides several ways by which we can retrieve data from database. One of them is dynamic query. You can easily fire complex query using dynamic query and it will reduce overhead of creating custom finder methods. Lets go step by step with easy example. If you want to fire simple AND query then here is the example.
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(MyCustomTable.class);
dynamicQuery.add(PropertyFactoryUtil.forName("status").eq("Pending")
dynamicQuery.add(PropertyFactoryUtil.forName("userId").eq(10122);

Above query will search in table MycustomTable for records which has status as Pending and userId as 10122. If you want to sort your records in particular order that also you can do.
Order defaultOrder = OrderFactoryUtil.desc("modifiedDate");
Order secondOrder = OrderFactoryUtil.desc("requestId");
dynamicQuery.addOrder(defaultOrder);
dynamicQuery.addOrder(secondOrder);

Above query will order records based on Modified Date and RequestId. Now if you want to fire some complex query like combination of or , And , Between and Like then here is the example. By using RestrictionFactoryUtil we can file OR , AND , Like and Between query.
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(MyCustomTable.class);

Criterion criterion = null;

criterion = RestrictionsFactoryUtil.like("subject", StringPool.PERCENT + "Test Subject"+ StringPool.PERCENT);

criterion = RestrictionsFactoryUtil.and(criterion, RestrictionsFactoryUtil.between("create_date",10/02/2012,10/03/2012));

criterion = RestrictionsFactoryUtil.or(criterion , RestrictionsFactoryUtil.eq("status", "Pending"));

dynamicQuery.add(criterion); 

As you can see above query will try to fetch those records which has subject like "Test Subject" and its created_date is in between the above dates or the records which has status as pending. To execute dynamic query.

List requestList = MyCustomTableLocalServiceUtil.dynamicQuery(dynamicQuery);


Viewing all articles
Browse latest Browse all 12

Trending Articles