简体   繁体   中英

XA Datasource does not create a transaction

I have an XA Datasource setup in Wildfly 8.2. It all works fine but when I call:

sql.query("LOCK TABLE table_name IN EXCLUSIVE MODE").execute();

I get an exception showing that Wildfly has not created a transaction:

org.postgresql.util.PSQLException: ERROR: LOCK TABLE can only be used in transaction blocks

If I manually create the transaction with a BEGIN and a COMMIT around my lock query, everything works as expected - but I would like Wildfly to do that for me automatically.

Why doesn't Wildfly create a transaction automatically and what do I need to do to fix it?


For reference, the code is called in a method like:

@RequestScoped
@Path("abc")
public class Controller {

@PUT
public Response m(Object data) {
  //HERE
}

If you want wildfly to create a transaction for you, use a ejb bean.. For your example, injecting a @Stateless session bean should work (since you are using RequestScoped, and stateless session beans have a similar lifecycle)

By default, each method of the stateless ejb will create a transaction for you, or if the client already has a current transaction, it will use it.

Code example:

@RequestScoped
@Path("abc")
public class Controller {

    @EJB
    private YourStatelessEJB statelessBean;

    @PUT
    public Response m(Object data) {
      //HERE
      statelessBean.doSomething(data)
}

@Stateless
@LocalBean
public class YourStatelessEJB {

    @PersistenceContext
    private EntityManager em;

    public YourStatelessEJB() {

    }

    public void doSomething(Object data) {
        // here you already have a transaction, created by the ejbcontainer
        ...
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM