Hibernate and Spring: value of many-to-many not inserted into generated table

强颜欢笑 提交于 2019-12-13 06:39:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!