多对多关系JPA,EJB和db中的新表

时间:2014-12-24 13:31:21

标签: jpa entity eclipselink ejb-3.1 javadb

我正在使用EJB,JPA和JSF2.2(NetBeans 8.0.2和GF 4.1)从事JavaEE(7)Entreprise应用程序 这是我在JavaDB中的设计:2个表与多对多的关系,所以一个新表" Avoir"是生成的。

a"文件"有几个" Critere"和" Critere"可以属于几个" Document"。 我的问题是当我使用Eclipselink 2.1从数据库生成实体类时,我只有一个" Document"和" Critere"课程,但没有" Avoir"类。

我的问题是,我怎样才能在" Avoir"桌子?

注意:这是我的两个班级的代码

Critere code:

@Entity
@Table(name = "CRITERE")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Critere.findAll", query = "SELECT c FROM Critere c"),
@NamedQuery(name = "Critere.findByIdcritere", query = "SELECT c FROM Critere c WHERE c.idcritere = :idcritere"),
// Others Query …
public class Critere implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "IDCRITERE")
// Other columns …
@JoinTable(name = "AVOIR", joinColumns = {
    @JoinColumn(name = "IDCRITERE", referencedColumnName = "IDCRITERE")}, inverseJoinColumns = {
    @JoinColumn(name = "IDDOC", referencedColumnName = "IDDOC")})
@ManyToMany
private Collection<Document> documentCollection;
// Other mappings ...

和文件代码:

@Entity
@Table(name = "DOCUMENT")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Document.findAll", query = "SELECT d FROM Document d"),
@NamedQuery(name = "Document.findByIddoc", query = "SELECT d FROM Document d WHERE d.iddoc = :iddoc"),
// Other Query …    
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "IDDOC")
private Integer iddoc;
// Other columns …

@ManyToMany(mappedBy = "documentCollection")
private Collection<Critere> critereCollection;
// Other mappings …
谢谢你:)

1 个答案:

答案 0 :(得分:0)

您无需担心这一点。 @ManyToMany是使用连接表(在您的情况下为AVOIR)实现的,持久性提供程序负责在数据库中将其连接起来。您的责任只是维护关系的双方,这意味着如果您向Critere添加一个Document,请确保Document在列表中也包含Critere

@JoinTable定义用于关系的表,joinColumns属性定义作为源表(CRITERE)的外键的列,inverseJoinColumns属性定义column是目标表的外键(DOCUMENT)。

Document doc = em.find(Document.class, 1L);
Critere cit = em.find(Critere .class, 1L);
// you just need to maintain both sides of the relationship
doc.getCritereCollection().add(crit);
crit.getDocumentCollection().add(doc);
em.merge(doc); // not really needed because these are attached entities (if executed inside of transaction)

这将在AVOIR表格中添加一行,两列中的值均为1