简体   繁体   中英

How to store relations in Spring Data JPA?

I have two entities with a many-to-may relationship:

@Entity
public class Entity1 {

    @Id
    @GeneratedValue
    private long id;

    // Some other fields

    @ManyToMany
    @JoinTable(
        name = "e1_e2",
        joinColumns = { @JoinColumn(name = "e1_id", referencedColumnName = "id") },
        inverseJoinColumns = { @JoinColumn(name = "e2_id", referencedColumnName = "id") }
    )
    private Set<Entity2> e2s = new HashSet<>();

    // Getters & setters

}

@Entity
public class Entity2 {

    @Id
    @GeneratedValue
    private long id;

    // Some other fields

    @ManyToMany(mappedBy = "e2s")
    private Set<Entity1> e1s = new HashSet<>();

    // Getters & setters

}

I have a webpage with a form for an Entity2 . When I select some Entity1 s from a multi-select and submit the form, I can see inside the controller that all selected Entity1 s are stored in e1s . Then I try to persist the new Entity2 using JpaRepository::save() . The Entity2 gets persisted, but not the relations to Entity1 . The save() call is wrapped in a service method that is annotated with @Transactional . Why are the relations not persisted?

This is the controller method that receives the Entity2 :

@RequestMapping(method = RequestMethod.POST)
public String createSupplier(@ModelAttribute final Entity2 e2) {
    service.create(e2);

    return "redirect:/";
}

And the service method:

@Transactional
public Entity2 create(Entity2 e2) {
    return repository.save(e2);
}

Change the annotation of e1s to @ManyToMany(cascade=CascadeType.ALL) in order to cascade the save operation to the related entities. See http://docs.oracle.com/cd/E19798-01/821-1841/bnbqm/index.html

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