Search code examples
hibernatejpahibernate-mapping

How to Model a Lookup Table with Composite Key using JPA


I have the following situation with a composite key in a lookup table:

LU_MASTER_TABLE
- [PK1] TYPE = type of value being looked up
- [PK2] ID = id of the value to lookup applying to that table
- DESC = the description of the id.

TABLE2>
- TYPE_A_ID
- TYPE_B_ID

What is the best way to create a one to one relationship using Spring JPA?


Solution

  • So far, below is the best I can come up with. Though it does not use the composite key so while it works, it doesn't really represent the DB structure.

     @Entity
     @Table(name= "LU_MASTER_TABLE")
     public class LuMasterTable {
    
       @Id
       @Column(name = "ID")
       protected String id;
    
       // Note I did not make typeField a PK even though it is in DB. 
       // Ideally it would be part of composite key, 
       // though I wasn't able to get composite key to work given 
       // the scenario here where upon joining with another table,
       // it must be a type of "constant".  See where clause in other
       // table below to see what I mean.
       @Column(name = "TYPE")
       protected String typeField;
    
     }
    

    table2

    @Entity
    @Table(name = "TABLE2")
    public class Table2{
    
     ...
    
      @OneToOne
      @JoinColumn(name="TYPE_A_ID")
      @Where(clause = "typeField = TYPE_A")
      protected LuMasterTable typeALuMasterTable;
    
      @OneToOne
      @JoinColumn(name="TYPE_B_ID")
      @Where(clause = "typeField = TYPE_B")
      protected LuMasterTable typeBLuMasterTable;
    
    }