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部分)。 –