I am trying to persist to multiple entities. Sample code below:
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;
}
}
Well, when I execute this query, the data didn't persist in database, but it shows the list of newly inserted data for small times, but data didn't save in database. I got no errors in console. Also put em.getTransaction().commit();
before return does not work. When I tried persisting on single entity and put em.getTransaction().commit();
, it worked perfectly. Like this:
public void save(Location location) {
log.info("Saving Location.");
em.persist(location);
em.getTransaction().commit();
}
What did I miss here?
As explained in this article , persist just schedules an entity state transition . The insert is executed during flush. If you don't commit the transaction, the flush will not be triggered automatically.
Anyway, you should always start a transaction, even if you plan to read data.
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.