【问题标题】:Data does not save while calling persist() multiple times多次调用 persist() 时数据不保存
【发布时间】:2017-06-11 18:08:34
【问题描述】:

我试图坚持到多个实体。示例代码如下:

public List<String> save(SalesInvoice salesInvoice, List<ClosingStock> closingStockList, Company company,
        Receipt receipt) {

    log.info("Saving Sales Invoice...");
    if (salesInvoice.getSalesChallanId() == null) {
        for (ClosingStock closingStock : closingStockList) {
            if (existingClosingStock(closingStock.getProduct().getId().toString()) == null) {
                em.persist(closingStock);
            } else {

            }
        }
    }
    em.persist(salesInvoice);
    receipt.setSalesInvoiceId(salesInvoice.getId());
    em.persist(receipt);
    return null;
}

// Edit: Add existingClosingStock method provided in comments

public ClosingStock existingClosingStock(String productId) { 
    try { 
        return (ClosingStock) em.createQuery("SELECT cv FROM ClosingStock cv WHERE cv.product.id=:productId") .setParameter("productId", productId).getSingleResult(); 
    } catch (NoResultException e) { 
        return null; 
    } 
} 

好吧,当我执行这个查询时,数据并没有保存在数据库中,但是它显示了新插入的数据列表一小段时间,但数据没有保存在数据库中。我在控制台中没有错误。在返回不起作用之前还要输入em.getTransaction().commit();。当我尝试坚持单个实体并输入em.getTransaction().commit(); 时,它运行良好。像这样:

public void save(Location location) {
    log.info("Saving Location.");
    em.persist(location);
    em.getTransaction().commit();
}

我错过了什么?

【问题讨论】:

  • 您能提供给我们existingClosingStock方法吗?您是否尝试过在调试模式下检查它是否返回 null 以执行持久化?
  • 你总是需要 tx.commit (和 tx.begin) 来符合 JPA 规范,但你没有展示出来。然后,您可以查看 JPA 提供者的日志并对其进行调试
  • @Matthieu public ClosingStock existingClosingStock(String productId) { try { return (ClosingStock) em.createQuery("SELECT cv FROM ClosingStock cv WHERE cv.product.id=:productId") .setParameter("productId ", productId).getSingleResult(); } catch (NoResultException e) { return null; } }
  • @Neil,我正在注入 Entity Manager,我已经做了 tx.begin()。
  • 您的代码指出,当您全部使用 em.getTransaction().commit();它完美地工作 - 尝试通过调用提交来使用您在有效方法中使用的相同事务范围。在 EntityManager 被告知与数据库同步之前,EntityManager 持久/合并什么都不做。这是通过显式 EntityManager.flush() 或在事务本身提交时完成的。

标签: java hibernate jpa


【解决方案1】:

正如this article 中所解释的,persist 只是安排一个entity state transition。在刷新期间执行插入。如果不提交事务,flush不会自动触发。

无论如何,您应该始终启动事务,即使您打算读取数据。

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2021-10-15
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多