Unidirectional ManyToMany mapping using Spring JPA

By | August 12, 2018
Questions:

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("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");

        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 🙂

Answers:

Leave a Reply

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