[英]output of many-to-many unidirectional and bidirectional mapping hibernate
在休眠状态下一对一关系的情况下,我们可以看到单向和双向情况下输出表存在差异,即只有一个表具有单向关联的外键,并且两个表都具有外键如果是双向的。 但是我看不到多对多单向和双向输出表的任何区别。 有人可以帮我吗? 谢谢。
实际上,使用多对多单向和双向时的表数是相同的。 主要的不同是使用双向对象时,可以获取列表或在两侧设置对象。 使用单向,您只需要从代码的一侧进行操作即可。 让我们看一个例子书和作者。 一本书有很多作者,作者可以写很多本书。 在示例中,我使用了Set,但是您可以使用List。 也可以 让我们看一下单向映射的映射:
@Entity
public class Author
{
private Long authorId;
private String authorName;
private Date dateOfBirth;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getAuthorId()
{
return authorId;
}
public void setAuthorId(Long authorId)
{
this.authorId = authorId;
}
@Column(name="author_name")
public String getAuthorName()
{
return authorName;
}
public void setAuthorName(String authorName)
{
this.authorName = authorName;
}
/**
* @return the dateOfBirth
*/
public Date getDateOfBirth() {
return dateOfBirth;
}
/**
* @param dateOfBirth the dateOfBirth to set
*/
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
@Entity
public class Book
{
private Long bookId;
private String bookTitle;
private List<Author> authors;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getBookId()
{
return bookId;
}
public void setBookId(Long bookId)
{
this.bookId = bookId;
}
@Column(name="book_title")
public String getBookTitle()
{
return bookTitle;
}
public void setBookTitle(String bookTitle)
{
this.bookTitle = bookTitle;
}
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="author_book", joinColumns=@JoinColumn(name="book_id"), inverseJoinColumns=@JoinColumn(name="author_id"))
public List<Author> getAuthors()
{
return authors;
}
public void setAuthors(List<Author> authors)
{
this.authors = authors;
}
}
您可以看到第三个表是使用两个表簿和author中的两个键创建的author_book。 因此,使用“单向”,“作者”列表只能从“书”中获取。 使用双向,您可以从“作者”访问“书籍”,也可以从“书籍”访问“作者”。 Book对象的映射应该相同。 作者看起来有点不同:
@Entity
public class Author
{
private Set<Book> books;
/**
* @return the books
*/
public Set<Book> getBooks() {
return books;
}
/**
* @param books the books to set
*/
public void setBooks(Set<Book> books) {
this.books = books;
}
//the rest is the same code like above
...
}
希望对您清楚!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.