JPA多对一,在引用表中使用常量值



我正在做Spring Boot项目并使用Spring - Boot -jpa (Hibernate实现)。我在配置实体之间的下列关系时遇到麻烦。

让我们假设我需要两个表之间的多对一(和反向一对多)关系(MySQL在这个例子中,table1逻辑上存储在各种其他表中的代码描述):

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`));
我在SQL中连接这两个表的方法是这样的:
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);
所以,我创建了这样的实体(减去getter和setter):
@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<Table2> 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;
}

但是它不起作用。(

这种关系可以在JPA中定义吗?如果有,请告诉我怎么做?

关于"连接常量值"的问题,我设法使它工作使用@Where Hibernate注释:

  • 如何用硬编码值替换@JoinColumn ?

    @Entity
    @Table(name = "a")
    public class A {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        public long id;
        @OneToMany
        @JoinColumn(name = "id", referencedColumnName = "id")
        @Where(clause = "blah = 'CONSTANT_VALUE'")
        public Set<B> b;
        protected A() {}
    }
    @Entity
    @Table(name = "b")
    public class B {
        @Id
        @Column(nullable = false)
        public Long id;
        @Column(nullable = false)
        public String blah;
        protected B() {}
    }
    

最新更新