Hibernate从其他数据库级联另一个Id



例如,我有级联到B的类A:

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, B有自己的id和包含id的列a

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不能设置为空。

谢谢!

当对共享映射使用派生标识符时,不仅需要在关系中添加@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,使持久性提供程序忽略将该字段写入数据库。

相关内容

  • 没有找到相关文章

最新更新