简体   繁体   中英

How to persist/commit entity to database immediately in Activiti Service Task

I have a need to persist(insert) a entity to database immediately when the save (or saveAndFlush) code is called.

However although the entity is created in the context it is not persisted in the database immediately.

We are using Spring Boot.

public interface MessageRepository extends JpaRepository<MessageEntity, Long> {
}

In the Service class

@Service
public class TestService {

@Autowired
    private MessageRepository messageRepository;

@Transactional
        public MessageEntity saveMessage(MessageEntity entity) throws Exception {
            entity = messageRepository.saveAndFlush(entity);
            return entity;
        }
}

Though the entity is created it is not persisted/committed to the database immediately.

We are facing this issue within the Activiti Tasks only.

Any feedback will be appreciated.

This worked.

@Component
public class MessageRepositoryCustomImpl implements MessageRepositoryCustom {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public MessageEntity saveImmediate(MessageEntity entity) {
        entityManager.persist(entity);
        return entity;
    }
}

One way of overcoming this situation is by taking advantage of the REQUIRES_NEW transaction attribute.

In your situation you would have to create a new repository:

public interface MessageRepositoryCustom{
   void saveAndFLush(MessageEntity ent);
}


public MessageRepositoryCustomImpl implements MessageRepositoryCustom{

   @Autowired
   private SessionFactory sessionFactory;

   @Transactional(propagation = Propagation.REQUIRES_NEW)
   void saveAndFLush(MessageEntity ent){
       Session session = sessionFactory.getCurrentSession();

       session.persist(ent);
   }
}

Then in your service you would use that repository:

@Transactional
        public MessageEntity saveMessage(MessageEntity entity) throws Exception {
            entity = messageRepositoryCutom.saveAndFlush(entity);

            // other processing

            return entity;
        }
}

Now after the messageRepositoryCutom.saveAndFlush method has finished processing the entity will be physically persisted in the database as it was created in a separate transaction which has been commited.

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