Hibernate Cascade 来自另一个数据库的另一个 Id

Hibernate Cascade another Id from another database

例如,我有 class A 级联到 B:

public class A{

    private String id;
    private Set<B> bs = new HashSet<B>(0);

    @Id
    @GenericGenerator(name = "seq_id", strategy = generators.SequenceIdGenerator")
    @GeneratedValue(generator = "seq_id")
    @COLUMN(name="id" unique = true, nullable = false, length = 28)
    public void getId(){
        return this.id;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "A")
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE, CascadeType.PERSIST})
    public void getBs(){
        return bs;
    }
}

我有 B,它有自己的 ID 和一个包含来自 A

的 ID 的列
public class B

    String id; 
    String aId;
    A a;

    @Id
    @GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
    @GeneratedValue(generator = "seq_id")
    @Column(name = "ID", unique = true, nullable = false, length = 28)
    public String getId() {
        return this.id;
    }

    @Column(name = "A_ID", nullable = false, length = 28)
    public String getAId() {
        return aId;
    }

    public void setAId(String aId) {
         this.aId = aId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "A_ID", nullable = false, insertable = false, updatable = false)
    @MapsId("aId")
    public Admission getAdmission() {
        return this.admission;
    }

    public void setAdmission(Admission admission) {
    this.admission = admission;
    }

如何在保存 A 时自动分配 aId?我想设置 aId,但我总是收到一条错误消息,指出 A_ID 不能设置为 null。

谢谢!

在共享映射中使用派生标识符时,您不仅需要在关系中添加 @MapsId 注释,还需要使用 @Id 注释对引用关系 ID 的字段进行注释。

查看操作方法(已省略 setter):

public class B {
    String id;
    String aId;
    A a;

    @Id
    @GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
    @GeneratedValue(generator = "seq_id")
    @Column(name = "ID", unique = true, nullable = false, length = 28)
    public String getId() {
        return this.id;
    }

    @Id
    public String getAId() {
        return aId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "A_ID", nullable = false)
    @MapsId("aId")
    public A getA() {
        return this.a;
    }
}

另一个错误是您将关系注释为 updatable = falseinsertable = false,这使得持久性提供程序忽略了将该字段写入数据库。