1

I am working on a requirement in which user can send messages to multiple people, I have to save those messages in a message table.
I am using JPA entityManager for persisting objects and Hibernate as a persistence provider and Spring declarative transaction management.

Even I am executing the persist() method for three times it is saving only one row in the table. I don't know what should I do to save all the messages. It is not displaying any exception message.

Following is my declarative transaction management configuration in applicationContext.xml

  <tx:advice id="txAdvice" >

    <tx:attributes>

        <tx:method
            name="*"
            propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<aop:config>

    <aop:pointcut
        id="messageServiceOperation"
        expression="execution(* com.abhinow.message.services.*.*(..))" />

    <aop:advisor
        advice-ref="txAdvice"
        pointcut-ref="messageServiceOperation" />
</aop:config>

Following is code in my service class MessageService.java

  private void saveMultipleMessages(SentMessage message) {
    String[] toAddresses = message.getMultipleDestinations().split(",");
    for(String to: toAddresses) {
        message.setTo(to);
    saveMessage(message);
    }
}

public void saveMessage(SentMessage message) {
    messageRepository.saveSentMessage(message);
}

Following is code in my MessageRepository.java

  @Repository
  public class MessageRepository {

   @PersistenceContext
   EntityManager entityManagerFactory;

   public void saveSentMessage(SentMessage message) {

    entityManagerFactory.persist(message);

    }
      }

Any help would be appreciated. Thanks in advance

1 Answer 1

1

It looks like you are re-using the same SentMessage object in your for loop. My guess is that JPA will detect that it already persisted this object and will not persist it again.

Try something like this:

private void saveMultipleMessages(SentMessage message) {
    String[] toAddresses = message.getMultipleDestinations().split(",");
    for(String to: toAddresses) {
        SentMessage toSave = message.withToAddress(to);
        saveMessage(toSave);
    }
}

Where "withToAddress" creates a new SentMessage object based on the current one, but with a different to address. When you use this technique, you can make SentMessage immutable, which often has advantages over mutable objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.