There are times when you want to handle multiple Liferay API calls as a single, atomic transaction. For example, let’s say you have a business process that has the following 3 steps:
- Create an Organization.
- Add a Role to the User.
- Update the User’s status.
Let’s say steps 1 & 2 complete successfully, but step 3 fails for some reason. In this case, you should roll back the previous 2 steps.
To do this in Liferay, simply create a new Service Builder project and add all your API calls inside the *ServiceImpl class and make sure the method throws either a SystemException or a PortalException. No other config changes are needed to package these calls into a single transaction.
Here is an example below.
For testing, if “bad” is passed in for the username, the method will throw a SystemException. This will cause the previous statements in the method to rollback. Of course, remove that statement before deploying this code.
public void update(User user, long[] roleIds, String orgName)
throws SystemException, PortalException {
long orgId = CounterLocalServiceUtil.increment(Organization.class.getName());
Organization org = OrganizationLocalServiceUtil.getService().
createOrganization(orgId);
org.setName(orgName);
OrganizationLocalServiceUtil.getService().updateOrganization(org);
UserLocalServiceUtil.getService().updateUser(user);
if (user.getFirstName().equals("bad")) {
throw new SystemException("Exception thrown due to firstName = 'bad'");
}
RoleLocalServiceUtil.getService().addUserRoles(user.getUserId(), roleIds);
}