Hibernate和Spring:多对多的值不插入到生成的表中 [英] Hibernate and Spring: value of many-to-many not inserted into generated table

查看:108
本文介绍了Hibernate和Spring:多对多的值不插入到生成的表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Spring有一些经验,但对于Hibernate来说,我完全是新手,特别是与Spring结合使用:
我想在两个表之间建立多对多关系(作者,出版物)。表格已生成,但没有插入任何内容......



Author.java的一部分:

  @ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name =writes,joinColumns = {@JoinColumn(name =authorId)},inverseJoinColumns = {@JoinColumn (name =publicationId)})
private Set< Publication> publications = new HashSet< Publication>();

部分Publication.java:

  @ManyToMany(mappedBy =publications)
private Set< Author> authors = new HashSet< Author>();

有没有我忘记的东西?

谢谢!!!!

编辑

以下是将所有内容保存到我的数据库的代码:

  @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;


解决方案




  • 将您的实体与会话相关联。如果你只是创建你的对象,hibernate不知道是否将它们保存到数据库。这就是为什么你应该调用 session.save(..) / entityManager.persist(..)(取决于是否您使用JPA)。

  • 事务 - 在hibernate中的每个操作都需要一个事务,因此您必须通过实体管理器/ session



我建议阅读一个教程,它将解释这些基本原则。


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";
}

解决方案

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.

这篇关于Hibernate和Spring:多对多的值不插入到生成的表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆