如果 ID 不存在,则 JPA spring boot 函数中的 UPDATE 查询错误以插入新行,否则用新值更新该行

Deepjyoti De

我在尝试更新行时遇到问题。我正在使用邮递员在我的表中插入或更新一行。所以我的代码就像 ID 已经存在于行中一样,用新值更新它,否则插入该行。

产品.java

@Entity(
        name = "Products"
)
@Table(
        name = "products"
)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Products {
    @Id
    @SequenceGenerator(
            name = "product_sequence",
            sequenceName = "product_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "product_sequence"
    )
    @Column(
            updatable = false
    )
    Integer id;
    @Column(
            nullable = false
    )
    String name;
    float price;
    int cid;

    public Products(String name, float price, int cid) {
        this.name = name;
        this.price = price;
        this.cid = cid;
    }

    public String toString() {
        return "Products{ id = " + this.id + " name = " + this.name + " price = " + this.price + " cid = " + this.cid + " }";
    }
}

ProductsRepository.java

public interface ProductsRepository extends JpaRepository<Products, Integer> {

    @Query("select p.name from Products p where p.id = ?1")
    List<String> findProductByCategory(Integer id);

    @Modifying(clearAutomatically = true)
    @Query("update Products p set p.id =:id, p.name =:name, p.price =:price, p.cid =:cid where p.id =:id")
    void updateProducts(@Param("id") Integer id, @Param("name") String  name, @Param("price") float price, @Param("cid") int cid);
}

产品服务.java


@Service
public class ProductsService {

    private final ProductsRepository productsRepository;

    @Autowired
    public ProductsService(ProductsRepository productsRepository) {
        this.productsRepository = productsRepository;
    }

    public void addNewProduct(Products product) {
        if(productsRepository.existsById(product.getId())==true)
            productsRepository.updateProducts(product.getId(), product.getName(), product.getPrice(), product.getCid());
        else
            productsRepository.save(product);
    }
}

产品控制器.java


@RestController
@RequestMapping(path = "/store/")
class ProductsController {

    private final ProductsService productsService;

    @Autowired
    public ProductsController(ProductsService productsService) {
        this.productsService = productsService;
    }

    @PostMapping(path = "/add/products")
    public void addNewProduct(@RequestBody Products product) {
        productsService.addNewProduct(product);
    }

}

但是在 postman 中尝试 POST 时,出现以下错误: {"timestamp":"2021-07-03T16:35:11.459+00:00","status":500,"error":"Internal Server Error","path":"/store/add/products"}

还有终端中的错误:

ERROR 7108 --- [nio-8090-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query] with root cause
javax.persistence.TransactionRequiredException: Executing an update/delete query
安尼什夏尔马

在服务类的addNewProduct方法中添加@Transactional

像这样使用

@Service 公共类 ProductsService {

private final ProductsRepository productsRepository;

@Autowired
public ProductsService(ProductsRepository productsRepository) {
    this.productsRepository = productsRepository;
}

@Transactional
public void addNewProduct(Products product) {
    if(productsRepository.existsById(product.getId())==true)
        productsRepository.updateProducts(product.getId(), product.getName(), product.getPrice(), product.getCid());
    else
        productsRepository.save(product);
 }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章