I’m creating a Spring boot app using Spring JPA on a OneToMany database relationship. It is a skincare routine builder where a routine is made up of many products. I am trying to create a method to delete a single product from the routine based on the foreign key and name field of the product class any help would be much appreciated
@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<>();
}
child entity
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??
}
small snippet of my controller
@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);
}
I have tried orphanRemoval and a few methods from guides but I can’t get it to work
>Solution :
Modify your Routine
class to include a method that searches and removes a product based on the product name:
@Entity
@Table(name = "routines")
public class Routine {
// ... (other fields)
public void removeProductByName(String productName) {
products.removeIf(product -> product.getName().equals(productName));
}
// ... (getters and setters)
}
Then, update your controller to utilize the method from the Routine
class and call it when deleting a product:
@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);
}
}
By using the removeProductByName
method within your Routine
class, you can remove a specific product by name from the list of products associated with the routine.