spring - 在@Transactional 中的事务期间提交

标签 spring hibernate jpa transactions transactional

是否可以在标记为 Spring 的 的方法中执行提交? @事务 ?

@PersistenceContext
private EntityManager em;

@Transactional(propagation = Propagation.REQUIRED)
public void saveMembersWithMultipleCommits(List<Member> members)
    throws HibernateException
{
    Iterator<Member> it = members.iterator();
    while (it.hasNext())
    {
        while (it.hasNext())
        {
            Member wsBean = it.next();
            em.persist(wsBean); // overall commit will be made after method exit
            log.info("Webservices record " + wsBean + " saved. " + i++);
        }
    }
}

我想在说每 500 个项目后提交给 DB。在上述背景下这可能吗?

最佳答案

不,您需要以编程方式使用,例如 TransactionTemplate API。阅读更多 here .

它看起来像

while (it.hasNext())
{
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            int counter = 0;
            while (it.hasNext() && counter++ < 500) {
                Member wsBean = it.next();
                em.persist(wsBean);
                log.info("Webservices record " + wsBean + " saved. " + i++);
            }
        }
    );
}

关于spring - 在@Transactional 中的事务期间提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12897882/

相关文章:

java - 使用 IntelliJ REST 客户端测试 Spring MVC POST 会导致 415

java - 错误 : "Another unnamed CacheManager already exists in the same VM" Using Spring, Jersey 和 ehCache

java - OSGI 容器中的数据源

java - 如何避免创建多余的实体?

hibernate - java.lang.ClassNotFoundException : org. hibernate 代理.EntityNotFoundDelegate

java - 如何向 Micronaut 项目添加第二个数据源?

exception - 为什么我无法捕获 EJB 异常?

java - Spring 数据 jpa,jparepository 返回字符串列表代替 DTO 对象

date - 无法在 Eclipselink 上合并日期

java - 如何根据 Java 对象的两个或多个字段为 hibernate 生成唯一的 Id?