2

I want to delete specific record using Field Name

Table : Dummy Entity

  • Field Id
  • Field Name

    public void deleteLocation(req, res){
    String getLocationName = request.getParameter("locationName");
    Location locationToDelete = new LocationImpl();
    locationToDelete.setLocationName(getLocationName);
    LocationLocalServiceUtil.deleteLocation(locationToDelete);
    }
    

It's not showing me any error but the record doesn't get deleted. Please hep me out.

Vinita Shah
  • 118
  • 2
  • 13

2 Answers2

2

The simplest way to achieve this is to add <finder> node for that specific field in service.xml, as following (saying Location is your entity name, name is your field name and Name is the name of finder entry in service.xml) and build service:

<column name="name" type="String" />

<finder name="Name" return-type="Collection">
    <finder-column name="name" />
</finder>

On successful build, it will create CRUD operations in your service based on that column. Now you can find following methods in your LocationUtil.java:

findByName,
removeByName,
countByName,

Create following (new) method in LocationLocalServiceImpl.java:

public void deleteLocationsByName(String name){
    try{
        LocationUtil.removeByName(name);
    }catch(Exception ex){
        // log your exception
    }
}

Again, on building service, this method will be available for use in your action class from LocationLocalServiceUtil.java, where you can call it like:

public void deleteLocation(req, res){
    String locationName = request.getParameter("locationName");
    LocationLocalServiceUtil.deleteLocationsByName(locationName);
}

That's it, you have added custom finder method to your service.

Parkash Kumar
  • 4,710
  • 3
  • 23
  • 39
  • @Vinita Shah, Other way is [***CUSTOM SQL QUERIES***](https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/developing-custom-sql-queries) as answered by joaco1977 – Parkash Kumar Feb 23 '16 at 06:19
1

If you want to remove an element by id, you can do it by the "LocalServiceUtil.delete(id)" If you want to remove an elements by other field than id, you need to do a custom Query for that, you can search in the portal soruce for the file: portal.xml containing this example:

<sql id="com.liferay.portal.service.impl.ResourceBlockLocalServiceImpl.deleteResourceBlock">
        <![CDATA[
            DELETE FROM
                ResourceBlock
            WHERE
                (referenceCount <= 0) AND
                (resourceBlockId = ?)
        ]]>
    </sql>

You can see here how to implement a custom query:

https://dev.liferay.com/develop/tutorials/-/knowledge_base/6-2/developing-custom-sql-queries

joaco1977
  • 126
  • 7