简体   繁体   中英

Unidirectional ManyToMany mapping using Spring JPA

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 :)

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:

  1. Remove the cascade from annotation.

&

  1. Save Recipes first and the add them in the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM