hibernate Spring JPA -移除单个子对象的方法

arknldoa  于 2023-10-23  发布在  Spring
关注(0)|答案(1)|浏览(129)

我正在OneToMany数据库关系上使用SpringJPA创建一个Sping Boot 应用程序。这是一个护肤常规建设者,其中一个常规是由许多产品。我试图创建一个方法来删除一个单一的产品从例行的基础上的外键和名称字段的产品类的任何帮助将不胜感激

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "routines")
public class Routine {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String type; 

    @OneToMany(targetEntity = Product.class, orphanRemoval = true, cascade = CascadeType.ALL)
    @JoinColumn(name = "routine_fk", referencedColumnName = "id")
    private List<Product> products = new ArrayList<>();
}

子实体

public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String category; // enum list : cleanser, toner, moisturiser, sunscreen, serum....

    @Column(nullable = false)
    private String brand;

    @Column(nullable = false)
    private int size;

    @Column()
    private String review; // only show this in get all products tab??
}

我的控制器的一个小片段

@DeleteMapping("{id}/{name}")
    public ResponseEntity<String> deleteRoutineProduct(@PathVariable("id") Long routineId, @PathVariable("name") String name){

        productService.deleteProduct(routineId, productName);
        return new ResponseEntity<>("Product deleted successfully.",HttpStatus.OK);
    }

我已经尝试过去除污垢和一些方法,从指南,但我不能让它工作

uurity8g

uurity8g1#

修改您的Routine类,以包含一个根据产品名称搜索和删除产品的方法:

@Entity
@Table(name = "routines")
public class Routine {

    // ... (other fields)

    public void removeProductByName(String productName) {
        products.removeIf(product -> product.getName().equals(productName));
    }

    // ... (getters and setters)
}

然后,更新您的控制器以利用Routine类中的方法,并在删除产品时调用它:

@DeleteMapping("{id}/{name}")
public ResponseEntity<String> deleteRoutineProduct(@PathVariable("id") Long routineId, @PathVariable("name") String name){

    Optional<Routine> optionalRoutine = routineRepository.findById(routineId);

    if (optionalRoutine.isPresent()) {
        Routine routine = optionalRoutine.get();
        routine.removeProductByName(name);
        routineRepository.save(routine);
        return new ResponseEntity<>("Product deleted successfully.", HttpStatus.OK);
    } else {
        return new ResponseEntity<>("Routine not found.", HttpStatus.NOT_FOUND);
    }
}

通过在Routine类中使用removeProductByName方法,可以按名称从与例程关联的产品列表中删除特定产品。

相关问题