Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9012769
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T03:05:30+00:00 2026-06-16T03:05:30+00:00

I have a RESTful API that makes use of an entity class annotated with

  • 0

I have a RESTful API that makes use of an entity class annotated with @EntityListners. And in the EntityListner.java, I have a method annotated with @PostPersist. So, when that event fires, I want to extract all the information regarding the entity that just got persisted to the database. But when I try to do that, Glassfish is generating an exception and the method in EntityListner class is not executing as expected. Here is the code

public class EntityListner {
private final static String QUEUE_NAME = "customer";
@PostUpdate
@PostPersist
public void notifyOther(Customer entity){
    CustomerFacadeREST custFacade = new CustomerFacadeREST(); 
    Integer customerId = entity.getCustomerId();
    String custData = custFacade.find(customerId).toString();
    String successMessage = "Entity added to server";
    try{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
      //  channel.basicPublish("", QUEUE_NAME, null, successMessage .getBytes()); 
        channel.basicPublish("", QUEUE_NAME, null, custData.getBytes());  
        channel.close();
        connection.close();


    }
    catch(IOException ex){

    }
    finally{

    }
  }    
} 

If I send the commented out successMessage message instead of custData, everything works fine.

http://www.objectdb.com/java/jpa/persistence/event says the following regarding the entity lifecycle methods, and I am wondering if that is the situation here.

To avoid conflicts with the original database operation that fires the entity lifecycle event (which is still in progress) callback methods should not call EntityMan­ager or Query methods and should not access any other entity objects

Any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T03:05:31+00:00Added an answer on June 16, 2026 at 3:05 am

    As that paragraph says, the standard does not support calling entity manager methods from inside entity listeners. I strongly recommend building custData from the persisted entity, as Heiko Rupp says in his answer. If that is not feasible, consider:

    • notifying asynchronously. I do not really recommend this as it probably depends on timing to work properly:
    public class EntityListener {
        private final static String QUEUE_NAME = "customer";
    
        private ScheduledExecutorService getExecutorService() {
            // get asynchronous executor service from somewhere
            // you will most likely need a ScheduledExecutorService
            // instance, in order to schedule notification with
            // some delay. Alternatively, you could try Thread.sleep(...)
            // before notifying, but that is ugly.
        }
    
        private void doNotifyOtherInNewTransaction(Customer entity) {
            // For all this to work correctly,
            // you should execute your notification
            // inside a new transaction. You might
            // find it easier to do this declaratively
            // by invoking some method demarcated
            // with REQUIRES_NEW
            try {
                // (begin transaction)
                doNotifyOther(entity);
                // (commit transaction)
            } catch (Exception ex) {
                // (rollback transaction)
            }
        }
    
        @PostUpdate
        @PostPersist
        public void notifyOther(final Customer entity) {
            ScheduledExecutorService executor = getExecutorService();
            // This is the "raw" version
            // Most probably you will need to call
            // executor.schedule and specify a delay,
            // in order to give the old transaction some time
            // to flush and commit
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    doNotifyOtherInNewTransaction(entity);
                }
            });
        }
    
        // This is exactly as your original code
        public void doNotifyOther(Customer entity) {
            CustomerFacadeREST custFacade = new CustomerFacadeREST(); 
            Integer customerId = entity.getCustomerId();
            String custData = custFacade.find(customerId).toString();
            String successMessage = "Entity added to server";
            try {
                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost("localhost");
                Connection connection = factory.newConnection();
                Channel channel = connection.createChannel();
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                channel.basicPublish("", QUEUE_NAME, null, custData.getBytes());  
                channel.close();
                connection.close();
            }
            catch(IOException ex){
            }
            finally {
            }
        }    
    } 
    
    • registering some post-commit trigger (my recommendation if Heilo Rupp answer is not feasible). This is not timing dependant because it is guaranteed to execute after you have flushed to database. Furthermore, it has the added benefit that you don’t notify if you end up rolling back your transaction. The way to do this depends on what you are using for transaction management, but basically you create an instance of some particular instance and then register it in some registry. For example, with JTA it would be:
    public class EntityListener {
        private final static String QUEUE_NAME = "customer";
    
        private Transaction getTransaction() {
            // get current JTA transaction reference from somewhere
        }
    
        private void doNotifyOtherInNewTransaction(Customer entity) {
            // For all this to work correctly,
            // you should execute your notification
            // inside a new transaction. You might
            // find it easier to do this declaratively
            // by invoking some method demarcated
            // with REQUIRES_NEW
            try {
                // (begin transaction)
                doNotifyOther(entity);
                // (commit transaction)
             } catch (Exception ex) {
                // (rollback transaction)
             }
        }
    
        @PostUpdate
        @PostPersist
        public void notifyOther(final Customer entity) {
            Transaction transaction = getTransaction();
            transaction.registerSynchronization(new Synchronization() {
                @Override
                public void beforeCompletion() { }
    
                @Override
                public void afterCompletion(int status) {
                    if (status == Status.STATUS_COMMITTED) {
                        doNotifyOtherInNewTransaction(entity);
                    }
                }
            });             
        }
    
        // This is exactly as your original code
        public void doNotifyOther(Customer entity) {
            CustomerFacadeREST custFacade = new CustomerFacadeREST(); 
            Integer customerId = entity.getCustomerId();
            String custData = custFacade.find(customerId).toString();
            String successMessage = "Entity added to server";
            try {
                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost("localhost");
                Connection connection = factory.newConnection();
                Channel channel = connection.createChannel();
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                channel.basicPublish("", QUEUE_NAME, null, custData.getBytes());  
                channel.close();
                connection.close();
            }
            catch(IOException ex){
            }
            finally {
            }
        }    
    }
    

    If you are using Spring transactions, the code will be very similar, with just some class name changes.

    Some pointers:

    • ScheduledExecutorService Javadoc, for triggering asynchronous actions.

    • transaction synchronization with JTA: Transaction Javadoc and Synchronization Javadoc

    • EJB transaction demarcation

    • the Spring equivalents: TransactionSynchronizationManager Javadoc and TransactionSynchronization Javadoc.

    • And some Spring documentation on Spring transactions

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When designing a RESTful API that uses a datastore that makes use of auto-generated
I have a custom implementation of a RESTful API for a PHP application that
We have a RESTful API that we are doing in MVC3. We would like
I am developing RESTful API for my application. All getters (that use HTTP GET)
I have an ASP.NET MVC 4 application that needs to use an existing API
I have created a rails application that has a simple RESTful json API. This
I have an Activity that will query a RESTful API every x seconds (polls
I have a Django app that's serving up a RESTful API using tasty-pie. I'm
I have a class that I would like to expose through a Jersey RESTful
I want to add user authentication to my restful api that I have created

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.