Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA foreign key without relationship

Tags:

java

jpa

I have two entity Mail and Attachment. I would like to create a constraint between them but without mapping a relationship.

For example:

class Mail {

    @Id
    private String id;

    ...
} 

class Attachment {

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

    @Id
    private String id;

    ...
}

So this is only a temporary example just to explain. In this case how can I make JPA creates the contraint without to be forced to map Mail inside Attachment?

I don't want to do this:

class Attachment {

    @Id
    @ManyToOne
    private Mail mail;

    @Id
    private String id;

    ...
}
like image 245
dash1e Avatar asked Jun 12 '16 07:06

dash1e


1 Answers

JPA creates the constraint and relationship between two entities by the relationship annotation such as @OneToMany or @ManyToOne . Without these annotations , you have to manually enforce the constraint and relationship by yourself.

For example,you can have a factory method on Mail to create an Attachement Implement their constraint in this factory method and ensure that an Attachement can only be created by this method.

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;
   }
}

Then implement a service class to coordinate all the things about Mail's business use-cases.Client should use this service class to manage mail.For example:

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); 
    }              
 }
like image 110
Ken Chan Avatar answered Oct 13 '22 18:10

Ken Chan