问题
I've got a bit of experience with spring, but I'm completely new to Hibernate, especially in combination with Spring: I want to have a Many-to-Many relationship between two tables (author, publication). The table is generated, but nothing is inserted...
Part of Author.java:
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "writes", joinColumns = {@JoinColumn(name = "authorId")}, inverseJoinColumns = {@JoinColumn(name = "publicationId")})
private Set<Publication> publications = new HashSet<Publication>();
part of Publication.java:
@ManyToMany(mappedBy = "publications")
private Set<Author> authors = new HashSet<Author>();
Is there something I forgot?
Thanks!!!!
Edit
here's the code which should save everything to my database:
@RequestMapping(value = PATHELEM + "/insertTest", method = RequestMethod.POST)
public String addAuthor(@ModelAttribute("object") DatabaseObject object,
BindingResult result) {
authorService.addAuthor(object.getAuthor());
publicationService.addPublication(object.getPublication());
return PATHELEM + "/insertEntryForm";
}
回答1:
You are missing two important things:
- associating your entities with a session. If you just create your objects, hibernate can't know whether to save them to db. That's why you should call
session.save(..)
/entityManager.persist(..)
(depending on whether you use JPA). - transaction - every manipulation in hibernate needs a transaction, so you have to start one via the entity manager / session
I'd suggest reading a tutorial, which will explain these basic principles.
来源:https://stackoverflow.com/questions/13591778/hibernate-and-spring-value-of-many-to-many-not-inserted-into-generated-table