jpa spring引导函数中的更新查询出错,如果id不存在,则插入新行,否则使用新值更新行

2vuwiymt  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(385)

我在尝试更新行时遇到问题。我正在使用postman在我的表中插入或更新一行。因此,我的代码是这样的:如果id已经存在于行中,则使用新值更新它,否则插入该行。

products.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);
}

productsservice.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);
    }
}

productscontroller.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 ”中发布时,出现以下错误: {"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
pxq42qpu

pxq42qpu1#

在服务类的addnewproduct方法处添加@transactional
像这样使用

@Service
public class 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);
     }
}

相关问题