0

I need to do multiple writes to DB under single transaction using Liferay 7.1. Basically, my question is would this work?

@Component(service = MyService.class)
public class MyService {

    private OrganizationLocalService localService;

    @Reference(unbind = "-")
    protected void setOrganizationLocalService(OrganizationLocalService localService) {
        this.localService = localService;
    }

    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void doInTransaction() {
        try {
            localService.createOrganization(...);
            localService.updateOrganization(...);
            // more
        catch (IllegalArgumentException e) {
            // rollback logic
        }
    }
}

There are also Liferay event listeners built to be part of the service calls used to manipulate Liferay entities. Those event listeners will do additional work like sending messages to Kafka topics, etc. And I am not sure if introducing transactions would not disrupt the work of these listeners.

jimmayhem
  • 355
  • 2
  • 7
  • Here you have another question in stackoverflow with different alternatives to create a transaction: - https://stackoverflow.com/questions/67201619/how-can-i-do-a-transactional-method-in-liferay-7-3 – jorgediaz-lr Jun 22 '22 at 06:23

1 Answers1

1

By default in Liferay, every method at LocalService level is transactional.

Then, you have to collect all tasks in a single localservice method to ensure a single transactional enviroment.

@Transactional annotation is not effective as you have tryed to do. Here is not a Spring enviroment.

Daniele Baggio
  • 2,157
  • 1
  • 14
  • 21
  • If I'm not mistaken, it's not _every_ method that's transactional, but those starting with certain action verbs, e.g. `add`, `update`, `delete`, and maybe a few others... (this is from ancient memory). I'd also go with a wrapper LocalService - there you're naturally in the same environment. And a transaction once started, is kept active. – Olaf Kock Jun 21 '22 at 09:45
  • No matter which word the method name starts, every localservice method is transactional. – Daniele Baggio Jun 21 '22 at 10:14
  • Checking [the tx-required element](https://learn.liferay.com/reference/latest/en/dxp/definitions/liferay-service-builder_7_4_0.dtd.html#tx-required) it looks like they _might_ be READ-, but not for WRITE transactional: "The tx-required element has a text value that will be used to match method names that require transactions. By default, the methods: add*, check*, clear*, delete*, set*, and update* require propagation of transactions. All other methods support transactions but are assumed to be read only...." (shortened, note the deprecation notice). – Olaf Kock Jun 21 '22 at 10:35
  • Caught it ! @OlafKock yes, it's a hidden gem I have totally forget. tx-required it's deprecated but it's still active reading the docs, is it ? – Daniele Baggio Jun 22 '22 at 04:50