Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

378
Views
Spring data jpa @ManyToOne orphanRemoval=true doesn't delete

Situation: Got Books and categories. Each category can have n books. Want to create new, update or delete books from category. If category is empty delete it from db. Currently insert, update, and delete books.

Problem: orphanRemoval=true doesn't delete category if it is empty.

@Entity
@Table(name = "book")
@Getter
@Setter
public class BookEntity implements DBEntity, Serializable {

    @Id
    private Integer id;
    private String bookname;
    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.DETACH, CascadeType.REFRESH})
    @JoinColumn(name = "categoryid", referencedColumnName = "id")
    private CategoryEntity categoryEntity;

    public Integer getId() {
        return this.id;
    }
}

@Entity
@Table(name = "category")
@Getter
@Setter

public class CategoryEntity implements DBEntity, Serializable {
    @Id
    private Integer id;
    private String categoryName;

    @OneToMany(cascade = CascadeType.REMOVE, mappedBy = "categoryEntity", orphanRemoval = true)
    private Set<BookEntity> bookEntitySet = new HashSet<BookEntity>(0);

}

@Transactional
public interface CategoryDAO extends CrudRepository<CategoryEntity, Integer> {
}

@Transactional
public interface BookDAO extends CrudRepository<BookEntity, Integer> {
}

Thanks for any help

p.s.
Tried:
didnt help:
Spring + JPA @OneToMany with orphanRemoval
looks stupid - deleting book from category (in case 2-n foreign key wont work):
https://hellokoding.com/jpa-one-to-many-relationship-mapping-example-with-spring-boot-maven-and-mysql/
Nothing mentioned:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!