JPA创建了一个由关系注释如@OneToMany
或@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;
}
}
然后实现服务类,以协调所有关于邮件的业务用cases.Client的事情应该使用此服务类来管理mail.For例如:
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);
}
}
使用FlywayDB或Liquibase创建您架构,而不是让JPA去做。无论如何,您都需要将包含不想丢失的数据的生产模式从一个版本迁移到下一个版本。 –
我会看看它,谢谢。无论如何,有没有解决我的问题使用JPA?想知道。 – dash1e
不是我所知道的。但我也不明白为什么你不想要一个ManyToOne关联(以及为什么你需要创建这个ID的ManyToOne部分)。 –