Reputation: 618
In my project I would like to have ManyToMany unidirectional mapping. To do so I've created User and Recipe entities and repositories for them (using Spring JPA repositories). Now I'd like to populate my database with some sample entries. Once I start spring-boot application, error occurs:
org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.demo.database.Recipe
Here are my User and Recipe classes:
-- User --
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String email;
@NotNull
@Size(min = 8)
private String password;
@ManyToMany(cascade = CascadeType.ALL)
private Set<Recipe> favouriteRecipes = new HashSet<>();
private User() {}
public User(String email, String password) {
this.email = email;
this.password = password;
}
}
-- Recipe --
@Data
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String title;
private Recipe() {}
public Recipe(String title) {
this.title = title;
}
}
and here is how I add rows to database:
@Component
public class DatabaseInitializer implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Override
public void run(String... args) throws Exception {
User u1 = new User("[email protected]", "admin123");
User u2 = new User("[email protected]", "admin123");
Recipe r1 = new Recipe("Chicken curry");
Recipe r2 = new Recipe("Spaghetti bolognese");
u1.getFavouriteRecipes().add(r1);
u1.getFavouriteRecipes().add(r2);
u2.getFavouriteRecipes().add(r1);
u2.getFavouriteRecipes().add(r2);
userRepository.save(u1);
userRepository.save(u2);
}
}
I've tried to follow this tutorial but there the guy uses hibernate instead of Spring repositories so that's why I'm stuck here. I really don't know where I am wrong.
Any help would be appreciated :)
Upvotes: 1
Views: 2882
Reputation: 3619
When you're saving User u2
then Hibernate is trying to save Recipes r1 and r2
again(as it has already saved it while saving User u1
). This is happening because @ManyToMany
annotation present in User class as User
is appearing to be the parent of Recipe
which is not the case as Recipies
could be common between Users
.
Solution:
cascade
from annotation.&
favoriteRecipe
collection.Following links could be helpful:
A beginner’s guide to JPA and Hibernate Cascade Types
How to persist @ManyToMany relation - duplicate entry or detached entity
Upvotes: 2