我有两个实体Mail和Attachment。我想在它们之间创建约束,但不映射关系。
例如:
class Mail {
@Id
private String id;
...
}
class Attachment {
@Id
// @... constraint with Mail.id ???
private String mailId;
@Id
private String id;
...
}
Run Code Online (Sandbox Code Playgroud)
因此,这只是一个临时示例,仅供说明。在这种情况下,如何使JPA创建约束而不被迫在Mail内部映射Attachment?
我不想这样做:
class Attachment {
@Id
@ManyToOne
private Mail mail;
@Id
private String id;
...
}
Run Code Online (Sandbox Code Playgroud)
@OneToManyJPA 通过或等关系注释创建两个实体之间的约束和关系@ManyToOne。如果没有这些注释,您必须自己手动强制执行约束和关系。
例如,你可以有一个工厂方法来Mail创建一个Attachement在这个工厂方法中实现它们的约束并确保只能Attachement通过这个方法创建。
public class Mail{
@Id
private String id;
public Attachement createAttachement(){
return new Attachement(id);
}
}
public class Attachement{
@Id
private String id;
@Column(name="mail_id")
private String mailId;
/***************************************************************************
I will put all the domain class in the same package and make the
constructor as package scope to reduce the chance that this
object is created by other class accidentally except Mail class.
**************************************************/
Attachement(String mailId){
this.mailId = mailId;
}
}
Run Code Online (Sandbox Code Playgroud)
然后实现一个服务类来协调有关邮件业务用例的所有事情。客户端应该使用这个服务类来管理邮件。例如:
public class MailService{
private EntityManager em;
@Transcational
public void createMailWithAttachement(){
Mail mail = new Mail(xxxx);
em.persist(mail);
Attachement attachement = mail.createAttachement();
em.persist(attachement);
}
@Transcational
public void newAttachmentOnMail(String mailId, XXXXX){
Mail mail = em.find(mailId, Mail.class);
if (mail == null){
throws new ApplicationException("Mail does not exist.Please Check");
}
Attachement attachement = mail.createAttachement();
em.persist(attachement);
}
}
Run Code Online (Sandbox Code Playgroud)