2016-06-12 78 views
2

我有兩個實體MailAttachment。我想在它們之間創建一個約束,但不映射關係。沒有關係的JPA外鍵

例如:

class Mail { 

    @Id 
    private String id; 

    ... 
} 

class Attachment { 

    @Id 
    // @... constraint with Mail.id ??? 
    private String mailId; 

    @Id 
    private String id; 

    ... 
} 

所以這只是一個暫時的例子只是爲了說明。在這種情況下,我如何才能讓JPA創建約束而不必被迫在Attachment內映射Mail

我不想這樣做:

class Attachment { 

    @Id 
    @ManyToOne 
    private Mail mail; 

    @Id 
    private String id; 

    ... 
} 
+2

使用FlywayDB或Liquibase創建您架構,而不是讓JPA去做。無論如何,您都需要將包含不想丟失的數據的生產模式從一個版本遷移到下一個版本。 –

+0

我會看看它,謝謝。無論如何,有沒有解決我的問題使用JPA?想知道。 – dash1e

+0

不是我所知道的。但我也不明白爲什麼你不想要一個ManyToOne關聯(以及爲什麼你需要創建這個ID的ManyToOne部分)。 –

回答

2

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); 
    }    
} 
+0

和DB上的約束? – dash1e

+1

我會手動將'Attachment.mail_id'設置爲'Mail.id'的FK約束。 –

+0

如何在JPA自動創建模式後手動添加它? – dash1e