gpt4 book ai didi

java - 在 hibernate 中加入复合主键的某个属性

转载 作者:行者123 更新时间:2023-12-02 08:15:40 25 4
gpt4 key购买 nike

我正在使用 hibernate,并且我有两个表(遗留的,它们无法重组),如下所示

表A

@Entity
@Table(name = "tableA")
public Class TableA implements Serializable {
@EmbeddedId private TableAId tableAId;

@OneToOne(mappedBy = "tableA")
private TableB tableB;

// getters, setters, hashCode and equals ommited
}

表A的复合ID

@Embeddable
public class TableAId implements Serializable {
protected int id1;
protected String id2;
protected int id3;
// getters, setters, hashCode and equals ommited
}

表B

@Entity
public class TableB implements Serializable {
@OneToOne
@JoinColumn(name = "tableB", referencedColumnName = "id3")
protected TableA tableA;
// getters, setters, hashCode and equals ommited
}

从上面的代码中可以看出,我需要表 B 使用表的组合键的一个或多个(不是全部)属性来连接表 A。我已经尝试过以下三种方法,但没有成功:

  1. 与上面的代码完全相同。
  2. 像这样更改referencedColumnName值

    referencedColumName = "tableAId.id3"
  3. 在 TableA 的 pojo 实体中添加复合复合键的属性,如下所示:

    // TableA
    @Column(name = "id1", insertable = false, updatable = false)
    private Integer id1;

如果这可能的话??如果有任何帮助,我们将不胜感激!!

最佳答案

我认为 JPA 注释 @MapsId 可能适合您:

http://docs.oracle.com/javaee/6/api/javax/persistence/MapsId.html

在 TableA 类中,尝试对 tableB 属性执行以下操作:

@MapsId("id3")
@OneToOne(mappedBy = "tableA")
private TableB tableB;

同时从 TableB 类的 tableA 属性中删除 @JoinColumn 注释。

关于java - 在 hibernate 中加入复合主键的某个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com