【发布时间】:2020-05-25 12:15:29
【问题描述】:
我正在学习 JPA,我发现我们有一些功能已经存在于 Jparepository 中,例如 save、saveAll、find、findAll 等,但没有像 update 这样的功能,
我遇到了一种需要更新表的情况,如果值已经存在,否则我需要在表中插入记录。
我创造了
@Repository
public interface ProductInfoRepository
extends JpaRepository<ProductInfoTable, String>
{
Optional<ProductInfoTable> findByProductName(String productname);
}
public class ProductServiceImpl
implements ProductService
{
@Autowired
private ProductInfoRepository productRepository;
@Override
public ResponseMessage saveProductDetail(ProductInfo productInfo)
{
Optional<ProductInfoTable> productInfoinTable =
productRepository.findByProductName(productInfo.getProductName());
ProductInfoTable productInfoDetail;
Integer quantity = productInfo.getQuantity();
if (productInfoinTable.isPresent())
{
quantity += productInfoinTable.get().getQuantity();
}
productInfoDetail =
new ProductInfoTable(productInfo.getProductName(), quantity + productInfo.getQuantity(),
productInfo.getImage());
productRepository.save(productInfoDetail);
return new ResponseMessage("product saved successfully");
}
}
如您所见,如果记录是新的,我可以保存该记录,但是当我尝试保存表中已经存在的记录时,它会给我与 primarykeyviolation 相关的错误,这很明显。我检查了一下,我们可以通过创建 entitymanager 对象或 jpa 查询来进行更新,但如果我不想同时使用它们怎么办。我们还有其他方法吗?
更新我还添加了EntityManager的实例并尝试合并代码
@Override
public ResponseMessage saveProductDetail(ProductInfo productInfo)
{
Optional<ProductInfoTable> productInfoinTable =
productRepository.findByProductName(productInfo.getProductName());
ProductInfoTable productInfoDetail;
Integer price = productInfo.getPrice();
if (productInfoinTable.isPresent())
{
price = productInfoinTable.get().getPrice();
}
productInfoDetail =
new ProductInfoTable(productInfo.getProductName(), price, productInfo.getImage());
em.merge(productInfoDetail);
return new ResponseMessage("product saved successfully");
但没有错误,日志中没有执行更新语句,有什么可能的原因吗? }
【问题讨论】:
标签: jpa spring-data-jpa