Hibernate:插入ManyToMany,在关系表中生成ID

时间:2012-05-04 09:12:07

标签: java hibernate jpa

我有桌子(书籍和作者有很多关系)

图书
ID
book_name

AUTHORS
ID
author_name

BOOKS_AUTHORS
ID
book_id
author_id

我在实体上映射此表

class Books  
{  
   @Id  
   long id;  

  @Column(name = "author_name")
   String name;


   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "BOOKS_AUTHORS", 
              joinColumns = @JoinColumn(name = "book_id"),
              inverseJoinColumns = @JoinColumn(name = "author_id"))  
   List<Authots> authors;  

// setter, getters, adder  
}  

class Authors  
{  
   @Id  
   long id;  

   @Column(name = "author_name")
   String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "BOOKS_AUTHORS", 
              joinColumns = @JoinColumn(name = "author_id"),
              inverseJoinColumns = @JoinColumn(name = "book_id"))  
   List<Books> books;  

// setter, getters, adder  
}  

现在,我尝试下一步

public void addAuthor(final String bookName, final Author author)
{  
      final Book book = // get book from database by bookName
      if (book == null)
         throw new DataNotFoundException("Book not found :(");
      author.addBook(book);
      book.addAuthor(author);  
      entityManager.persist(author);  
}  

1)我得到的例外是BOOKS_AUTHORS记录的ID必须不是NULL 2)如何为关系表生成ID(ising sequance generator)BOOKS_AUTHORS

4 个答案:

答案 0 :(得分:11)

您无法使用@ManyToMany创建包含id字段的连接表。

如果连接表中的id字段是必需的,则必须为该表创建一个特殊的实体类(例如BookAuthor),并将其与书籍和作者用@ManyToOne / {{连接起来1}}关系。

否则您需要从@OneToMany表中删除id字段。

答案 1 :(得分:1)

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

如果未使用Hibernate映射books_authors,则使用数据库端自动id增量器。例如:

ALTER table book_authors CHANGE id long NOT NULL AUTO_INCREMENT;

答案 2 :(得分:0)

尝试使用Projection

                  session.CreateCriteria(typeof (BOOKS_AUTHORS))
                           .SetProjection(Projections.Max("Id"))
                           .UniqueResult()

并添加它+1 :) Sory它的.net代码我不熟悉java希望它能帮到你。

答案 3 :(得分:0)

SpringBoot 1.5.3 spring-boot-starter-data-jpa 中,您可以使用注释stringify。对于您的示例,它应该如下所示:

{@OrderColumn(name = "id")}