How to carry out imperative transactions in websockets for Quarkus


How?

Step 1:

# src/main/resources/application.properties

# add following line
quarkus.websocket.dispatch-to-worker = true

Step 2:

// in wherever your @ServerEndpoint class is

// add @Transactional annotation to the endpoint
// that carries out transactions
@Transactional
@OnMessage
public void onMessage(String message) {
  // example transaction stuff...
  var exampleitem = new ExampleItem();
  exampleitem.persist();
}

Background

I was playing with panache entities, and I plan to use it on websockets. However, I found out that @Transactional does not work for websocket without some configurations.

@Transactional works on rest endpoints like @GET and @POST, but on websocket it would throw BlockingOperationNotAllowedException: Cannot start a JTA transaction from the IO thread. Turns out you just need websocket to dispatch to worker.

This has taken me a while to find out, and I hope it helps whoever need this next.


Last modified

Date: 2023-07-26

Copyright © 2023 Martinmimi