CodexBloom - Programming Q&A Platform

Issues with JPA CascadeType.ALL causing unexpected deletions in Java Spring Data JPA

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-06-06
java spring jpa hibernate Java

I'm collaborating on a project where I'm optimizing some code but I'm facing an issue with JPA where using `CascadeType.ALL` on my relationships is leading to unintended deletions. I have two entities, `Author` and `Book`, where each `Author` can have multiple `Book` entries. When I delete an `Author` instance, I expect all associated `Books` to be deleted, which is intended; however, when I persist a new `Author` with an already existing `Book`, the `Book` gets deleted. Here's a snippet of my entity classes for reference: ```java @Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true) private List<Book> books = new ArrayList<>(); // getters and setters } @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "author_id") private Author author; // getters and setters } ``` When I try to save a new `Author` with an existing `Book` like this: ```java Author newAuthor = new Author(); newAuthor.setBooks(Arrays.asList(existingBook)); authorRepository.save(newAuthor); ``` The `existingBook` seems to be deleted from the database. I’ve tried changing the cascade type to `CascadeType.PERSIST` only, but that does not resolve my issue. I also verified that the `Book` is not null and already present in the database before persisting the `Author`. The only thing I can see is that the `existingBook` is being treated as a new entity due to the cascading behavior. Is there a way to prevent this unintended deletion while still allowing for the cascading of new `Book` entities? What am I missing here? My development environment is Windows 11. Could this be a known issue? The project is a REST API built with Java.