【问题标题】:JPA @ManyToOne joining on part of composite primary keyJPA @ManyToOne 加入复合主键的一部分
【发布时间】:2021-08-11 06:49:37
【问题描述】:

我有两个要加入的表。 比方说 TableA 和 TableB。

表A

@Entity
@Table(name = "TableA")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TableA {

    @Id
    @EmbeddedId
    private TableA.PrimaryId id = new TableA.PrimaryId();

    @Column(name = "COL1")
    private Integer col1;   
   
    @ManyToOne
    @JoinColumn(name = "ID1")

    private TableB tableB;

    @Data
    @Embeddable
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class PrimaryId implements Serializable {
        @Column(name = "ID1")
        private Integer id1;

        @Column(name = "ID2")
        private Integer id2;
    }
}

表B

@Entity
@Table(name = "TableB")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TableB {
    @Id
    @EmbeddedId
    private PrimaryId id = new PrimaryId();

    @Column(name = "COLUMN1")
    private String column1;

    @Data
    @Embeddable
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class PrimaryId implements Serializable {
        @Column(name = "ID1")
        private Integer id1;

        @Column(name = "KEY2")
        private Integer key2;

        @Column(name = "KEY3")
        private Integer key3;

        @Column(name = "KEY4")
        private Long key4;
    }
}

问题在于 TableB 有 复合主键(4 列),但我只需要在 1 列 (ID1) 上加入。 它不是标准连接,它是部分主键连接。

所以会报错:

nested exception is org.hibernate.AnnotationException: A Foreign key refering TableB from TableA has the wrong number of column. should be 4

如果我试试这个

@ManyToOne
@JoinColumn(name = "ID1", referencedColumnName = "ID1", updatable=false, insertable=false)

我得到另一个错误

nested exception is org.hibernate.AnnotationException: referencedColumnNames(ID1) of TableA.TableB referencing TableB not mapped to a single property

我已经在类似的帖子中寻找答案,但没有发现任何有用的东西:(

所以我很感激任何帮助...

【问题讨论】:

标签: java hibernate jpa spring-data-jpa


【解决方案1】:

如果我有错误请纠正我,但可能有多个 TableB 实体具有相同的“ID1”值,所以这里不适合 toOne 关系,对吧?

我想检索所有“相关”TableB 实体列表的一种简单方法是分别查询特定的“ID1”,例如通过tableBRpository.findByIdId1(tableA.id.id1)

【讨论】:

  • 是的,你是对的。所以你认为@JoinColumn 不可能吗?我需要通过 TableA 访问 TableB 列,以便在同时使用 TableA 列和 TableB 列的常见查询中使用它
  • 我没有,但是这个链接可以提供一些关于如何在休眠查询中加入不相关实体的想法:thorben-janssen.com/how-to-join-unrelated-entities
猜你喜欢
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多