简体   繁体   English

如何在Activiti服务任务中将实体立即保存/提交到数据库

[英]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. 我需要在调用save(或saveAndFlush)代码时立即将实体持久化(插入)到数据库中。

However although the entity is created in the context it is not persisted in the database immediately. 但是,尽管实体是在上下文中创建的,但它不会立即保留在数据库中。

We are using Spring Boot. 我们正在使用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. 我们仅在Activiti任务中面临此问题。

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. 解决这种情况的一种方法是利用REQUIRES_NEW事务属性。

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. 现在,在messageRepositoryCutom.saveAndFlush方法完成处理后,由于实体是在已提交的单独事务中创建的,因此实体将物理保留在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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