我在我的应用程序中使用EJB 3和JPA 2,我有2个实体,有许多关系,并希望坚持它们但幸运的是经过数小时的搜索并尝试我无法做到,所以这个是我的代码:
@Entity
public class Destinataire implements Serializable {
@Id
@Basic(optional = false)
@Size(min = 1, max = 50)
@Column(name = "ADRESSE")
private String adresse;
@OneToMany(mappedBy = "destinataire")
private Set<Envois> envoisSet;
//getters and setters
}
@Entity
public class Envois implements Serializable {
@EmbeddedId
protected EnvoisPK envoisPK = new EnvoisPK();
@Size(max = 4)
@Column(name = "TYPENVOIS")
private String typenvois;
@JoinColumn(name = "IDMAIL", referencedColumnName = "IDMAIL", insertable = false, updatable = false)
@ManyToOne(optional = false)
private MailAEnvoyer mailAEnvoyer;
@JoinColumn(name = "ADRESSE", referencedColumnName = "ADRESSE", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Destinataire destinataire;
}
@Embeddable
public class EnvoisPK implements Serializable {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "ADRESSE")
private String adresse;
@Basic(optional = false)
@NotNull
@Column(name = "IDMAIL")
private BigDecimal idmail;
}
@Entity
@Table(name = "MAILAENVOYER")
public class MailAEnvoyer implements Serializable {
private static final long serialVersionUID = 1L;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "IDMAIL")
private BigDecimal idmail;
@JoinTable(name = "ENVOIS", joinColumns = {
@JoinColumn(name = "IDMAIL", referencedColumnName = "IDMAIL")}, inverseJoinColumns = {
@JoinColumn(name = "ADRESSE", referencedColumnName = "ADRESSE")})
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
private Set<Destinataire> destinataireSet;
@OneToMany(mappedBy = "mailAEnvoyer", cascade = CascadeType.ALL)
private Set<Envois> envoisSet;
}
这就是我的进展方式:
Envois e = new Envois("CCI");
Destinataire dest = new Destinataire("adress");
destinataireService.create(dest);
e.setDestinataire(dest);
currentMailAEnvoyer.getEnvoisSet().add(e);
mailService.save(currentMailAEnvoyer);
但我总是得到一个例外,EnvoisPK有adresse和idmail null,
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("MAILING"."ENVOIS"."IDMAIL")
Error Code: 1400
Call: INSERT INTO ENVOIS (TYPENVOIS, IDMAIL, ADRESSE) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(entities.Envois[ envoisPK=entities.EnvoisPK[ adresse=null, idmail=null ] ])
答案 0 :(得分:1)
您可以在实体MailAEnvoyer中添加以下方法:
@PostPersist
public void postPersist() {
for (Envois e : envoisSet) {
e.getEnvoisPK().setIdmail(this.getIdmail());
}
}