Wednesday, April 1, 2015

JPA Relationship between Entities

I have a CompanyClass table and each class can only have one image saved in the filestore table in the database. And the image file saved in Filestore table only match one Companyclass. I would like to use JPA to do data retrieving, saving and removing.


This is a OneToOne mapping relationship in JPA. My entities are like this.

  @Entity   
  @Table(name="COMPANYCLASS", schema="xxx")   
  public class CompanyClass implements Serializable {   
    private static final long serialVersionUID = 1L;   
    @Id   
    @GeneratedValue(strategy=GenerationType.IDENTITY)   
    @Column(name="CLASS_ID",unique = true, nullable = false)   
    private Long classId;   
    @OneToOne (targetEntity=FileStore.class, cascade = CascadeType.ALL)   
    @JoinColumn(name="IMG_ID", referencedColumnName="FILE_ID")   
    private FileStore fileStore; 
    @Column(name="FILE_NAME")   
    private String fileName; 
   ....
    (get and set methods)   
   ....   


 @Entity  
 @Table(name="FILESTORE", schema="xxxx")  
 public class FileStore implements Serializable {  
      private static final long serialVersionUID = 1L;  
      @Id  
      @GeneratedValue(strategy=GenerationType.IDENTITY)  
      @Column(name="FILE_ID" ,unique = true, nullable = false)  
      private Long fileId;  
      @OneToOne(mappedBy="fileStore")  
      private CompanyClass companyClasses;  
 ....  
 (get and set method)       
 ....  

I specified my table primary key to self-incremented in the database side. So I use
 @GeneratedValue(strategy=GenerationType.IDENTITY) 

In this example, my CompanyClass is  the owner. So in the FileStore entity, it is mappedBy ="fileStore". This fileStore is the attribute in the CompanyClass.


  @JoinColumn
A Join Column in JPA is a column in the owner side entity that refers to a key (usually a primary key) in the non-owner or inverse entity.

In the CompanyClass entity, I have
 cascade = CascadeType.ALL
 This means the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

For example, if I want to insert a new companyclass with an image into database, I can just write code like this.

  EntityManager emgr;  
  CompanyClass cclass = new CompanyClass();  
            FileStore fileStore= new FileStore();  
            fileStore.setFileName = "Image.png";  
            cclass.setFileStore(fileStore);       
  emgr.persist(cclass);  
  emgr.close();  


No comments:

Post a Comment