0

例如,我有级联到 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 有它自己的 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 不能设置为空。

谢谢!

4

1 回答 1

1

当使用带有共享映射的派生标识符时,您不仅需要将@MapsId注释放在关系中,还需要使用注释来注释引用关系 id 的字段@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;
    }

    @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 = falseand insertable = false,从而使持久性提供程序忽略了将此字段写入数据库。

于 2017-04-24T11:14:18.880 回答