我有一个senario,其中有实体文章,实体作者和连接表Article_Author。文章和作者有很多关系(关于文章可以有很多作者,作者可以有很多文章)。 这是我的实体类: 作者类:
@Entity
@Table(name="AUTHOR")
@NamedQuery(name="Author.findAll", query="SELECT a FROM Author a")
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="AUTHOR_CODE")
private String authorCode;
private String nom;
//bi-directional many-to-many association to Article
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="ARTICLE_AUTHOR"
, joinColumns={
@JoinColumn(name="AUTHOR")
}
, inverseJoinColumns={
@JoinColumn(name="ART_REF")
}
)
private List<Article> article;
}
//getters and setters + hashcode and equals methods
文章类:
@Entity
@Table(name="ARTICLE_TEST")
@NamedQuery(name="ArticleTest.findAll", query="SELECT a FROM ArticleTest a")
public class ArticleTest implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="ART_REF")
private String artRef;
@Column(name="ART_TITRE")
private String artTitre;
//bi-directional many-to-many association to AutheurTest
@ManyToMany(mappedBy="articleTests", fetch=FetchType.EAGER)
private List<AutheurTest> autheurTests;
//getters and setters + hashcode and equals methods
}
以下是我创建文章并附加一位作者(用于测试)的代码:
//.....
AutheurTest aut1 = new AutheurTest();
AutheurTest aut2 = new AutheurTest();
aut1.setAutheurCode("1");
aut1.setNom("AUT1");
articlemodelBean.createautheurtest(aut1);
ArticleTest art1 = new ArticleTest();
art1.setArtRef("A");
art1.setArtTitre("ART1");
articlemodelBean.dmlArticle_test(art1,"insert"); //persist art1
AutheurTest newaut = articlemodelBean.getAuteurActive_test(aut1.getAutheurCode());
ArticleTest foundedart = articlemodelBean.findArticle_test(art1.getArtRef()); //getting the article
foundedart.getAutheurTests().add(newaut);
articlemodelBean.artaut(foundedart); //merge foudedart
//.....
所以我没有收到任何错误,文章和作者都被添加到数据库中!但外键未插入连接表。所以基本上作者没有附在文章上。