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

时间:2017-02-12 18:55:44

标签: java spring-boot spring-data-jpa spring-transactions activiti

当调用save(或saveAndFlush)代码时,我需要立即将实体持久化(插入)到数据库。

但是,虽然实体是在上下文中创建的,但它不会立即保留在数据库中。

我们正在使用Spring Boot。

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

在服务类

@Service
public class TestService {

@Autowired
    private MessageRepository messageRepository;

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

虽然创建了实体,但它不会立即持久化/提交到数据库。

我们仅在Activiti任务中遇到此问题。

我们将不胜感激。

2 个答案:

答案 0 :(得分:2)

这很有用。

@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;
    }
}

答案 1 :(得分:1)

克服这种情况的一种方法是利用REQUIRES_NEW事务属性。

在您的情况下,您必须创建一个新的存储库:

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);
   }
}

然后在您的服务中,您将使用该存储库:

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

            // other processing

            return entity;
        }
}

现在messageRepositoryCutom.saveAndFlush方法处理完毕后,实体将在数据库中物理保留,因为它是在已提交的单独事务中创建的。