sooribabu
sooribabu

Reputation: 33

How to implement referential integrity and cascading actions in liferay service xml file?

I have a requirement that I need to implement onDelete Cascade functionality with liferay service builder. How can I achieve this in liferay?

Upvotes: 1

Views: 317

Answers (1)

Gevatterjan
Gevatterjan

Reputation: 590

First of all:

onDelete Cascade is NOT a Liferay Service Builder functionality. It is a funtionality provided by your database.

Next: Liferay has the premise, that all data processing and evaluation should be done in the code, and NOT in the database.

Having said that:

Something similar to onDelete Cascade would be to implement a Model Listener. A ModelListener is listening to changes of a Model. (I know, misleading name ;) ) In this model listener, you would implement onAfterRemove. In the onAfterRemove goes your code for the deletion of related records.

Here is a small sample I have written. The code is listening to changes of the group object, and tries to delete the referenced ObjectGeodata object, if there is one present.

package de.osc.geodata.modellistener;

import com.liferay.portal.ModelListenerException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.model.BaseModelListener;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.ServiceContext;

import de.osc.geodata.model.ObjectGeodata;
import de.osc.geodata.service.ObjectGeodataLocalServiceUtil;

public class GroupModelListener extends BaseModelListener<Group> {

    private static final Log log = LogFactoryUtil.getLog(GroupModelListener.class);


    @Override
    public void onAfterRemove(Group model) throws ModelListenerException {
        try {
            ObjectGeodata objectGeodata = ObjectGeodataLocalServiceUtil.getObjectGeodata(model.getClassNameId(), model.getClassPK());
            if (objectGeodata != null) {
                ObjectGeodataLocalServiceUtil.deleteObjectGeodata(objectGeodata);
            }
        } catch (SystemException e) {
            log.warn("No GeodataObject found in Index.", e);
        }

        super.onAfterRemove(model);
    }

}

Upvotes: 3

Related Questions