title: JPA many-to-one with constant values in referenced table
body: <p>I'm doing Spring Boot project and use spring-boot-jpa (Hibernate implementation). I'm having trouble configuring following relation between entities.</p>
  
  <p>Let's assume I need many-to-one (and reversly one-to-many) relation between two tables (MySQL in this example, <code>table1</code> logically stores description for codes in various other tables) :</p>
  
  <pre><code>CREATE TABLE `table1` (
     `id` INT NOT NULL AUTO_INCREMENT,
     `ref_table` VARCHAR(50) NOT NULL,
     `ref_column` VARCHAR(50) NOT NULL,
     `code` VARCHAR(10) NOT NULL,
     `description` VARCHAR(100) NOT NULL,
     PRIMARY KEY (`id`),
     UNIQUE INDEX `u_composite1` (`ref_table` ASC, `ref_column` ASC, `code` ASC));
  
  CREATE TABLE `table2` (
     `id` INT NOT NULL AUTO_INCREMENT,
     `field1` VARCHAR(100) NULL,
     `code` VARCHAR(10) NOT NULL,
     PRIMARY KEY (`id`));
  </code></pre>
  
  <p>The way I join these two tables in SQL is like this:</p>
  
  <pre><code>SELECT t2.*, t1.description 
  FROM table2 t2 
  JOIN table1 t1 
    ON    ( t1.ref_table = 'table2'
        AND t1.ref_column = 'code' 
        AND t1.code = t2.code);
  </code></pre>
  
  <p>So, I created entities like this (minus the getters an setters):</p>
  
  <pre><code>@Entity
  @Table(name = "table1")
  public class Table1  implements Serializable {
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(unique = true, nullable = false)
      private int id;
  
      @Column(nullable = false, length = 10)
      private String code;
  
      @Column(length = 100)
      private String description;
  
      @Column(name = "ref_column", nullable = false, length = 50)
      private String refColumn;
  
      @Column(name = "ref_table", nullable = false, length = 50)
      private String refTable;
  
      @OneToMany(mappedBy = "table1")
      private List&lt;Table2&gt; table2;
  }
  
  @Entity
  @Table(name = "table2")
  public class Table2  implements Serializable {
      private static final long serialVersionUID = 1L;
  
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Column(unique = true, nullable = false)
     private int id;
  
     @Column(nullable = false, length = 45)
     private String field1;
  
     @ManyToOne(fetch=FetchType.LAZY)
     @Column(name = "code")
     @JoinColumns({
        @JoinColumn(name = "code", referencedColumnName = "code", nullable = false, updatable = false),
        @JoinColumn(name = "'table2'", referencedColumnName = "ref_table", nullable = false, updatable = false),
        @JoinColumn(name = "'code'", referencedColumnName = "ref_column", nullable = false, updatable = false)
     })
     private Table1 table1;
  
  }
  </code></pre>
  
  <p>But it doesn't work. :(</p>
  
  <p>Can this kind of relation even be defined in JPA?
  If so, please, how?</p>