Unidirectional ManyToMany mapping using Spring JPA

By | August 12, 2018

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 —

public class User {

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

    private String email;

    @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 —

public class Recipe {

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

    private String title;

    private Recipe() {}

    public Recipe(String title) {
        this.title = title;


and here is how I add rows to database:

public class DatabaseInitializer implements CommandLineRunner {

    private UserRepository userRepository;

    public void run(String... args) throws Exception {
        User u1 = new User("rick.astley@gmail.com", "admin123");
        User u2 = new User("john.doe@gmail.com", "admin123");

        Recipe r1 = new Recipe("Chicken curry");
        Recipe r2 = new Recipe("Spaghetti bolognese");





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 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *