【问题标题】:Mapping a bidirectional One-to-Many Hibernate Entity with JPA使用 JPA 映射双向一对多 Hibernate 实体
【发布时间】:2016-05-18 17:27:52
【问题描述】:

我正在尝试在 Hibernate 中映射双向的一对多关系。在构建日志中,我收到错误“实体映射中的重复列”。

产生错误的原因是什么?

实体源代码如下。一个有一个复合主键。我正在使用 Lombok 来生成 getter 和 setter。

关系:Award (One) --> AwardReceived (Many)

奖励实体

@Entity
@Table(name = "awards")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class Award implements Serializable {

    @Id
    @Column(name = "award_id")
    private Long awardId;

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "award")
    private Set<AwardReceived> awardsReceived;

    @Column(name = "award_type")
    private String awardType;

    @Column(name = "award")
    private String award;

    @Column(name = "description")
    private String description;

}

获奖实体

@Entity
@Table(name = "awards_received")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class AwardReceived implements Serializable{

    @EmbeddedId
    @JsonUnwrapped
    private AwardReceivedPk awardReceivedPk;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "award_id")
    private Award award;

    @Column(name = "award_name")
    private String awardName;

    @Column(name = "citation")
    private String citation;

}

AwardReceivedPk

@Embeddable
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class AwardReceivedPk implements Serializable{

    @JsonIgnore
    @Column(name = "client_no")
    private String clientNo;

    @Column(name = "award_id")
    private Long awardId;

    @Column(name = "year")
    private Long year;

}

【问题讨论】:

  • 您收到错误,因为在映射中使用了两次 award_id,
  • @shankarsh15 那么 JoinColumn 注释是用户定义的列名吗?

标签: java hibernate jpa spring-boot


【解决方案1】:

请尝试

@ManyToOne(cascade=CascadeType.ALL)
private Award award;

而不是

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "award_id")
private Award award;

【讨论】:

  • 这似乎奏效了。我的(不正确的)印象是 JoinColumn 注释指向连接表中的关系键。
  • 对,但它也在AwardReceived中创建列来处理加入条件。请检查您的表结构,它应包含 AwardReceived 中的列,其 ID 为 Award。 Hibernate 应该找到自己的 Award 的 id 列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多